I have working Windows Form application that gets a jpeg image from and website and displays it in an Image control. However, when I attempt to save the image to the file system using the Image.Save function, it creates the file but leaves it empty. Not sure what I'm doing wrong...
In the following, DownloadData() successfully retrieves a byte array containing the image.
byte[] imageData = DownloadData();
MemoryStream stream = new MemoryStream(imageData);
Image img = Image.FromStream(stream);
stream.Close();
picMain.Image = img;
string fname = @"C:\Users\mikec1\Pictures\Construction\Construction_" + Now.ToString("yyyyMMdd") + "_" + Now.ToString("HHmmss") + ".jpg";
picMain.Image.Save(fname, System.Drawing.Imaging.ImageFormat.Jpeg);
I get the same result if I execute the Save from the img object.
In fact, the application terminates upon execution of the last line, without apparently throwing an exception.
Save a picture or other image as a separate fileControl-click the illustration that you want to save as a separate image file, and then click Save as Picture. In the Save as type list, select the file format that you want. In the Save As box, type a new name for the picture, or just accept the suggested file name.
1. Right-click the picture that you want to save in a graphics file format, and then click Save as Picture. 2. In the Save as type list, select the graphics file format that you want.
Your problem is that an Image
instantiated using FromStream
requires the stream to remain open for the lifetime of the Image
. Get rid of stream.Close()
and it should be fine. See msdn for details.
I tried your code and it threw an ExternalException
, saying A generic error occurred in GDI+
, without any InnerException
, also creating an empty file. Omitting that line made the image show up on the form just fine. Changing .NET versions didn't seem to have any impact.
While I'm not sure why that happens see Simon's answer, you can simply avoid this problem entirely by using
System.IO.File.WriteAllBytes(fname, imageData);
instead of
picMain.Image.Save(fname, System.Drawing.Imaging.ImageFormat.Jpeg);
It should use less overhead also, since Image.Save
has to deal with image formats first before saving, and you already have your byte array right there.
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