Converting a JPEG image to a byte array - COM exception

user181813 picture user181813 · Sep 14, 2011 · Viewed 68.3k times · Source

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?

Answer

Samich picture Samich · Sep 14, 2011

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