【问题标题】:C# Image outofboundmemory exceptionC# 图像 outofboundmemory 异常
【发布时间】:2012-07-12 07:31:27
【问题描述】:

我尝试将二进制数据转换为 Image。这是我的代码:

 Byte[] bytes = (byte[])(reader["Avatar"]);
 fs1.Write(bytes, 0, bytes.Length);
 pictureBox1.Image = Image.FromFile("image.jpg");
 pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
 pictureBox1.Refresh();

但错误是行中超出内存异常:“pictureBox1.Image = Image.FromFile("image.jpg");” 我不知道为什么会这样,请帮助我

【问题讨论】:

标签: c# image


【解决方案1】:

试试这个方法:

    public Image ImageFromBytes(byte[] bytes)
    {
        using(var ms = new MemoryStream(bytes))
        {
          return Image.FromStream(ms);
        }
    }

【讨论】:

    【解决方案2】:

    如果 fs1 是一个流,您可能应该在下一行访问该文件之前关闭它。 请注意,您也可以在内存中创建图像并完全避开文件系统。

    【讨论】:

    • 对不起,我发布缺少代码:fs1.Close(); fs1 = null;
    【解决方案3】:

    您将CloseDispose 设为您的信息流:

    fs1.Write(bytes, 0, bytes.Length);
    //Make sure you closed your stream
    fs1.Close();
    // You should call Dispose too.
    fs1.Dispose();
    pictureBox1.Image = Image.FromFile("image.jpg");
    

    或将您的写入文件过程包含在using 块中:

    using (Stream fs1 ...)
    {
        ...
        fs1.Write(bytes, 0, bytes.Length);
    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多