Converting a JPEG image to a byte array - COM exception

24

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?

c#
wpf
image
com
file-io
asked on Stack Overflow Sep 14, 2011 by user181813 • edited Sep 14, 2011 by Zenwalker

4 Answers

53

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();
}
answered on Stack Overflow Sep 14, 2011 by Samich
22

Other suggestion:

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

Should be working not only with images.

answered on Stack Overflow Mar 6, 2014 by Hristo • edited Jul 19, 2014 by ann
5
public byte[] imageToByteArray(System.Drawing.Image imageIn)  
{   
 MemoryStream ms = new MemoryStream();     

 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);   
 return  ms.ToArray();   
}
answered on Stack Overflow Apr 4, 2013 by hizbul25 • edited May 29, 2013 by Adrian K.
3

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);
answered on Stack Overflow Feb 20, 2013 by Flangus

User contributions licensed under CC BY-SA 3.0