将JPEG图像转换为字节数组 - COM异常

use*_*813 21 c# com wpf file-io image

使用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(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

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

COMException未处理.句柄无效.(HRESULT异常:0x80070006(E_HANDLE))

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

Sam*_*ich 48

查看本文中的示例: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();
}
Run Code Online (Sandbox Code Playgroud)


Hri*_*sto 13

其他建议:

byte[] image = System.IO.File.ReadAllBytes ( Server.MapPath ( "noimage.png" ) );
Run Code Online (Sandbox Code Playgroud)

应该不仅适用于图像.


hiz*_*l25 5

public byte[] imageToByteArray(System.Drawing.Image imageIn)  
{   
 MemoryStream ms = new MemoryStream();     

 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);   
 return  ms.ToArray();   
}
Run Code Online (Sandbox Code Playgroud)