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.Wi
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();
}
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);
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
Other suggestion:
byte[] image = System.IO.File.ReadAllBytes ( Server.MapPath ( "noimage.png" ) );
Should be working not only with images.