Saturday, February 6, 2010

Get Oracle BLOB and save as JPG using ASP.NET

/*
The following code snippet shows how to retrieve an Oracle BLOB column data and save it as a JPEG file. Before using this code, you must create an OracleCommand object with a valid Oracle connection. To see how to create an OracleCommand and OracleConnection, see ADO.NET section of this site.
*/
public string ReadLob(OracleCommand cmd)
{

int actual = 0;
string acid = string.Empty;
OracleDataReader reader = cmd.ExecuteReader();
using(reader)
{
while (reader.Read()) //Obtain the a row of data.
{

//Obtain the LOB
acid = reader.GetString(0);
OracleLob blob = reader.GetOracleLob(1);

//to save the lob as a picture.. naming it by its ID
string filename = " \\" + acid + ".jpg ";
ListBox1.Items.Add(filename);

//file for buffered stream and the stream itself
Stream outputStream = File.OpenWrite(@filename);
BufferedStream bufferedOutput = new BufferedStream(outputStream);

//Example - Reading binary data (in chunks).
byte[] buffer = new byte[100];
while ((actual = blob.Read(buffer, 0, buffer.Length)) > 0)
{
bufferedOutput.Write(buffer, 0, buffer.Length);
bufferedOutput.Flush();
}
bufferedOutput.Close();
}//end of while
}
return acid;
}

No comments:

Post a Comment