关于C#:将JPEG图像转换为字节数组-COM异常

Converting a JPEG image to a byte array - COM exception

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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 was unhandled. The handle is invalid. (Exception from
HRESULT: 0x80070006 (E_HANDLE))

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


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

此外,最好使用System.Drawing

中的类

1
2
3
4
5
6
7
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();
}


其他建议:

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

不仅应与图像配合使用。


1
2
3
4
5
6
7
public byte[] imageToByteArray(System.Drawing.Image imageIn)  
{  
 MemoryStream ms = new MemoryStream();    

 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);  
 return  ms.ToArray();  
}

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

您可以将整个函数package在using {}块中,也可以使用其他BitmapFrame.Create(),例如:

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