Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image.Save does not save image data to file

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.

like image 575
Cyberherbalist Avatar asked Feb 02 '16 00:02

Cyberherbalist


People also ask

How do I save an image file?

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.

How do I save pictures on Windows 10?

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.


2 Answers

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.

like image 134
Simon MᶜKenzie Avatar answered Sep 21 '22 18:09

Simon MᶜKenzie


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.

like image 32
Gediminas Masaitis Avatar answered Sep 22 '22 18:09

Gediminas Masaitis