【发布时间】:2012-05-01 17:45:44
【问题描述】:
我正在尝试通过 HttpHandler 将图像输出到输出流,但它不断抛出 ArgumentException。我已经用谷歌搜索了这个问题并尝试了很多东西,但我仍然无法解决这个问题。无论如何,这是代码:
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.");
}
请注意,imageData 字节数组不为空,并且内存流正在正确填充。有什么想法吗?
更新:
这是GetTradeMarkImage 的代码... 请注意,图像以image 格式存储在SQL Server 数据库中。
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;
}
【问题讨论】:
-
字节数组很可能不为空,但这不等于它是正确。
GetTradeMarkImage的代码是什么样的,图片数据是什么格式的? -
当流没有有效的图像格式时也会出现此异常。
-
@JonSkeet:我更新了问题并包含了从数据库中获取图像的代码。