【问题标题】:Error : "Out of Memory ", when converting .jls image to byte[] array错误:“内存不足”,将 .jls 图像转换为 byte[] 数组时
【发布时间】:2012-10-17 05:34:10
【问题描述】:

我有这个函数可以将图像转换为字节数组。

  public byte[] imageToByteArray(System.Drawing.Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.MemoryBmp);
        return ms.ToArray();
    }

这是我调用函数的代码。

  private void btn_Click(object sender, EventArgs e)
    {
       inputPath=textbox1.text;

        try
        {
            System.Drawing.Image img = Image.FromFile(inputPath);
           byte[] str= imageToByteArray(img);
         }


     catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

当我运行程序或触发事件时,它会抛出一个异常,上面写着“内存不足” - 为什么会发生这种情况?

我正在使用这个函数来解码 .jls 图像(使用 JPEG-LS 算法压缩的图像)。所以这显然意味着该文件不受支持,对吧?你知道其他的选择吗?

【问题讨论】:

    标签: c# image memory image-conversion


    【解决方案1】:

    来自MSDN

    如果文件没有有效的图像格式或 GDI+ 没有 支持文件的像素格式,这个方法抛出一个 OutOfMemoryException 异常。

    更多:

    Image 类不支持位图中的 Alpha 透明度。至 启用 Alpha 透明度,使用每像素 32 位的 PNG 图像。

    有关支持格式的更多信息,请访问here

    【讨论】:

    • +1 表示评论,但这听起来不奇怪吗?我的意思是当这不是实际原因时报告 OOM 异常。我会认为像 InvalidOperationException 或类似的东西会更合适。
    • 我正在使用这个函数来解码 .jls 图像(使用 JPEG-LS 算法压缩的图像)。所以这显然意味着该文件不受支持,对吧?你知道还有其他选择吗?
    • @MrMoose:因为它是 GDI+ 包装器,所以异常来自 GDI+。或者更确切地说是错误代码。 GDI+ 只有大约 22 个错误代码 IIRC,而 OOM 错误代码可能意味着很多事情。有时它意味着OOM,有时它意味着其他东西。
    • 离奇。不过感谢您的澄清。
    • @Sani Huttunun :是的,我正在尝试在 C# 中实现 CharLS,显然他们不提供解压缩示例。
    【解决方案2】:

    试试这个图像到字节[]:

     byte[] str = File.ReadAllBytes("InputImagePath");
    
    private void btn_Click(object sender, EventArgs e)  
        {  
           inputPath=textbox1.text;  
    
            try  
            {  
              byte[] str= File.ReadAllBytes("inputPath");
            }  
    
    
         catch (Exception ex)  
            {  
                MessageBox.Show(ex.Message);  
            }  
        }  
    

    【讨论】:

      【解决方案3】:

      Out of Memory 异常非常不言自明。

      你可以试试下面的

      • 尝试不同尺寸的图片,观察系统在哪个尺寸范围内开始出现内存不足异常
      • 尝试处置您的MemoryStream

      示例

      public byte[] imageToByteArray(System.Drawing.Image imageIn)
      {
          using(MemoryStream ms = new MemoryStream()) 
          {
              imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.MemoryBmp);
              return ms.ToArray();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-21
        • 2013-01-28
        • 2011-12-05
        • 2018-02-23
        • 2013-06-01
        • 1970-01-01
        • 2014-09-08
        • 1970-01-01
        相关资源
        最近更新 更多