Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a JPEG image to a byte array - COM exception

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?

like image 400
user181813 Avatar asked Sep 14 '11 08:09

user181813


People also ask

How do I convert JPG to bytes?

Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

What is image byte array?

Images are binary data - this is easily represented as byte arrays. The image in the sample is stored in the database as a BLOB - not a string or location, that is, it is binary data.

How is an image stored in a byte array?

A byte array is just a collection of bytes. Theoretically, the contents of the byte array would be the same as what you'd see if you used a HEX editor to view the bytes of the corresponding image as saved on the disk.


2 Answers

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(); } 
like image 63
Samich Avatar answered Oct 06 '22 00:10

Samich


Other suggestion:

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

Should be working not only with images.

like image 36
Hristo Avatar answered Oct 05 '22 23:10

Hristo