Image.FromStream抛出ArgumentException:参数无效

时间:2012-04-20 06:14:26

标签: c# .net image stream

我正在尝试通过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;
    }

1 个答案:

答案 0 :(得分:1)

好的,现在您已经发布了GetTradeMarkImage代码,这几乎肯定是问题所在:

using (MemoryStream ms = new MemoryStream())
{
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, result);
    return ms.ToArray();
}

为什么您希望BinaryFormatter的值是有效的图像流?目前尚不清楚数据库中的内容(BLOB?)以及result的执行时类型(通过调试应该找到),但不应使用BinaryFormatter在这里。我怀疑你只是希望从数据库中获取原始数据,并将其放入字节数组中。

如果您很幸运,可能只能将result投射到byte[]开始。 (我不知道ExecuteScalar对blob做了什么,这显然不是“普通”ExecuteScalar方法。否则,您可能需要使用替代方法,打开DataReader并以此方式获取值。

相关问题