Converting a JPEG image to a byte array - COM exce

2019-02-03 02:31发布

Using C#, I'm trying to load a JPEG file from disk and convert it to a byte array. So far, I have this code:

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(); 
    }
}

However, executing line ARGH gives me the message:

COMException was unhandled. The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))

I don't think there is anything special about the file Lenna.jpg - I downloaded it from http://computervision.wikia.com/wiki/File:Lenna.jpg. Can you tell what is wrong with the above code?

4条回答
▲ chillily
2楼-- · 2019-02-03 03:09
public byte[] imageToByteArray(System.Drawing.Image imageIn)  
{   
 MemoryStream ms = new MemoryStream();     

 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);   
 return  ms.ToArray();   
}
查看更多
倾城 Initia
3楼-- · 2019-02-03 03:28

Check the examples from this article: http://www.codeproject.com/KB/recipes/ImageConverter.aspx

Also it's better to use classes from 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();
}
查看更多
欢心
4楼-- · 2019-02-03 03:29

Other suggestion:

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

Should be working not only with images.

查看更多
【Aperson】
5楼-- · 2019-02-03 03:34

The reason this error happens is because the BitmapFrame.Create() method you are using defaults to an OnDemand load. The BitmapFrame doesn't try to read the stream it's associated with until the call to encoder.Save, by which point the stream is already disposed.

You could either wrap the entire function in the using {} block, or use an alternative BitmapFrame.Create(), such as:

BitmapFrame.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
查看更多
登录 后发表回答