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.
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.