【问题标题】:Converting a JPEG image to a byte array - COM exception将 JPEG 图像转换为字节数组 - COM 异常
【发布时间】:2011-11-16 19:27:26
【问题描述】:

使用 C#,我正在尝试从磁盘加载 JPEG 文件并将其转换为字节数组。到目前为止,我有这个代码:

static void Main(string[] args)
{
    System.Windows.Media.Imaging.BitmapFrame bitmapFrame;

    using (var fs = new System.IO.FileStream(@"C:\Lenna.jpg", FileMode.Open))
    {
        bitmapFrame = BitmapFrame.Create(fs);
    }

    System.Windows.Media.Imaging.BitmapEncoder encoder = 
        new System.Windows.Media.Imaging.JpegBitmapEncoder();
    encoder.Frames.Add(bitmapFrame);

    byte[] myBytes;
    using (var memoryStream = new System.IO.MemoryStream())
    {
        encoder.Save(memoryStream); // Line ARGH

        // mission accomplished if myBytes is populated
        myBytes = memoryStream.ToArray(); 
    }
}

但是,执行ARGH 行给了我消息:

COMException 未处理。句柄无效。 (例外来自 HRESULT: 0x80070006 (E_HANDLE))

我认为文件Lenna.jpg 没有什么特别之处——我是从http://computervision.wikia.com/wiki/File:Lenna.jpg 下载的。你能说出上面的代码有什么问题吗?

【问题讨论】:

    标签: c# wpf image com file-io


    【解决方案1】:

    查看本文中的示例:http://www.codeproject.com/KB/recipes/ImageConverter.aspx

    另外最好使用来自System.Drawing的类

    Image img = Image.FromFile(@"C:\Lenna.jpg");
    byte[] arr;
    using (MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        arr =  ms.ToArray();
    }
    

    【讨论】:

    • 如果我不知道图像文件的确切类型,我该怎么做?我的意思是它是 JPEG 还是 GIF,我如何保存这两个文件?
    • 这很有帮助,但img.Save() 调用应该将img.RawFormat 作为第二个参数,而不是ImageFormat.Jpeg。上面的代码有效,但这应该可以帮助任何使用其他格式的人。
    【解决方案2】:

    发生此错误的原因是您使用的 BitmapFrame.Create() 方法默认为 OnDemand 加载。 BitmapFrame 在调用encoder.Save 之前不会尝试读取与其关联的流,此时流已经被释放。

    您可以将整个函数包装在 using {} 块中,或者使用替代的 BitmapFrame.Create(),例如:

    BitmapFrame.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    

    【讨论】:

      【解决方案3】:
      public byte[] imageToByteArray(System.Drawing.Image imageIn)  
      {   
       MemoryStream ms = new MemoryStream();     
      
       imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);   
       return  ms.ToArray();   
      }
      

      【讨论】:

        【解决方案4】:

        其他建议:

        byte[] image = System.IO.File.ReadAllBytes ( Server.MapPath ( "noimage.png" ) );
        

        不仅应该使用图像。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-16
          • 2013-05-19
          相关资源
          最近更新 更多