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.Wind开发者_开发技巧ows.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?
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.
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
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);
精彩评论