【问题标题】:Image.FromStream throws ArgumentException: Parameter is not validImage.FromStream 抛出 ArgumentException:参数无效
【发布时间】: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:我更新了问题并包含了从数据库中获取图像的代码。

标签: c# .net image stream


【解决方案1】:

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

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

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

如果你很幸运,也许可以将result 转换为byte[] 开始。 (我不知道ExecuteScalar 对blob 做了什么,这显然不是“正常的”ExecuteScalar 方法)。否则,您可能需要使用另一种方法,打开 DataReader 并以这种方式获取值。

【讨论】:

  • 嗯...是的,实际上我只想要数据库中的原始数据,然后我想在屏幕上显示图像。数据在数据库中存储为image
  • 转换字节[] 不起作用。 ExecuteScalar 只是企业库中相应方法的包装器。但除此之外,您认为我应该将数据存储在其他字段类型中吗?
  • @Kassem:嗯,我确实说过要通过调试找出result 的执行时间类型……什么 执行时间类型?在数据库中使用image 类型很好,但是您需要不同的代码来获取数据。在不知道result 的值的类型的情况下,很难说到底是什么。
  • result 的执行时间类型为byte[]
  • @Kassem:不,您不需要创建MemoryStream 并调用ToArray。只需返回演员 byte[] - 应该没问题。
猜你喜欢
  • 2019-02-26
  • 1970-01-01
  • 2012-12-04
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
相关资源
最近更新 更多