Images from SQL Server JPG/PNG Image Column not being Type Converted to Bitmap in HttpHandlers (cons
- by kanchirk
Our Silverlight 3.0 Client consumes Images stored/retrieved on the File System thorough ASP.NET HttpHandlers successfully.
We are trying to store and read back Images using a SQL Server 2008 Database. Please find the stripped down code pasted below with the Exception. "Bitmap is not Valid"
//Store document to the database
private void SaveImageToDatabaseKK(HttpContext context, string pImageFileName)
{
try
{
//ADO.NET Entity Framework
ImageTable documentDB = new ImageTable();
int intLength = Convert.ToInt32(context.Request.InputStream.Length);
//Move the file contents into the Byte array
Byte[] arrContent = new Byte[intLength];
context.Request.InputStream.Read(arrContent, 0, intLength);
//Insert record into the Document table
documentDB.InsertDocument(pImageFileName, arrContent, intLength);
}
catch
{
}
}
=The method to Read Back the Row from the Table and Send it back is below.=
private void RetrieveImageFromDatabaseTableKK(HttpContext context, string pImageName)
{
try
{
ImageTable documentDB = new ImageTable();
var docRow = documentDB.GetDocument(pImageName); //based on Imagename which is unique
//DocData column in table is **Image**
if (docRow!=null && docRow.DocData != null && docRow.DocData.Length > 0)
{
Byte[] bytImage = docRow.DocData;
if (bytImage != null && bytImage.Length > 0)
{
Bitmap newBmp = ConvertToBitmap(context, bytImage );
if (newBmp != null)
{
newBmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
newBmp.Dispose();
}
}
}
}
catch (Exception exRI)
{
}
}
// Convert byte array to Bitmap (byte[] to Bitmap)
protected Bitmap ConvertToBitmap(byte[] bmp)
{
if (bmp != null)
{
try
{
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap b = (Bitmap)tc.ConvertFrom(bmp); **//This is where the Exception Occurs.**
return b;
}
catch (Exception)
{
}
}
return null;
}