Cyberherbalist
Cyberherbalist

Reputation: 12309

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.

Upvotes: 4

Views: 5087

Answers (2)

Gediminas Masaitis
Gediminas Masaitis

Reputation: 3212

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.

Upvotes: 3

Simon MᶜKenzie
Simon MᶜKenzie

Reputation: 8664

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.

Upvotes: 4

Related Questions