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?
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.
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.
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.
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(); }
Other suggestion:
byte[] image = System.IO.File.ReadAllBytes ( Server.MapPath ( "noimage.png" ) );
Should be working not only with images.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With