I’m trying to output an image to the output stream through an HttpHandler but it keeps throwing an ArgumentException. I’ve googled the issue and tried so many things but I still couldn’t fix the problem. Anyway, here’s the code:
public void ProcessRequest(HttpContext context)
{
Int32 imageId = context.Request.QueryString["id"] != null ?
Convert.ToInt32(context.Request.QueryString["id"]) : default(Int32);
if (imageId != 0)
{
//context.Response.ContentType = "image/jpeg";
Byte[] imageData = this._imageInfoManager.GetTradeMarkImage(imageId);
using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
{
using (Image image = Image.FromStream(ms, true, true)) //this line throws
{
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
}
throw new ArgumentException("Image could not be found.");
}
Note that the imageData byte array is not empty and the memory stream is being filled up correctly. Any thoughts?
UPDATE:
Here’s the code for GetTradeMarkImage… Note that the images are stored in the an SQL Server database in the image format.
public Byte[] GetTradeMarkImage(Int32 id)
{
object result = DB.ExecuteScalar(SqlConstants.SqlProcedures.Request_GetImageById, id);
if (result != null)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, result);
return ms.ToArray();
}
}
return null;
}
Okay, now you’ve posted the
GetTradeMarkImagecode, that’s almost certainly the problem:Why would you expect the value of
BinaryFormatterto be a valid image stream? It’s not clear what’s in your database (a BLOB?) nor what the execution-time type ofresultis here (which you should find out by debugging) but you shouldn’t be usingBinaryFormatterhere. I suspect you just want to get the raw data out of the database, and put that into the byte array.If you’re lucky, you may just be able to cast
resulttobyte[]to start with. (I don’t know whatExecuteScalardoes with blobs, and this obviously isn’t the “normal”ExecuteScalarmethod anyway). Otherwise, you may need to use an alternative approach, opening aDataReaderand getting the value that way.