Saving image: A generic error occurred in GDI+. (vb.net)
I need to save an image after opening it in from an OFD. This is my code atm:
Dim ofd As New OpenFileDialog
ofd.Multiselect = True
ofd.ShowDialog()
For Each File In ofd.FileNames
Image.FromFile(File).Save("C:\Users\Jonathan\Desktop\e\tmp.png", Imaging.ImageFormat.png)
Next
And on the line Image.FromFile(File).Save("C:\Users\Jonathan\Desktop\开发者_StackOverflow社区e\tmp.png", Imaging.ImageFormat.png)
it comes up with the error.
(note: the application will be built on so that's just my first code and it will need to be saved not copied)
I'd check two things:
- That the directory you're saving to exists
- That you have write permissions to this directory
Opening or saving an Image puts a lock on the file. Overwriting this file requires you to first call Dispose() on the Image object that holds the lock.
I don't really understand your code but you'd have to do it this way:
For Each File In ofd.FileNames
Using img As Image = Image.FromFile(File)
img.Save("C:\Users\Jonathan\Desktop\e\tmp.png", Imaging.ImageFormat.Png)
End Using
Next
The Using statement ensures that the img object is disposed and the file lock is released.
The Image puts a lock.
For example, i used this buffer images to save in to a memorystream.
byte[] ImageData = new Byte[0];
if (BackGroundImage != null)
{
Bitmap BufferImage = new Bitmap(BackGroundImage);
MemoryStream ImageStream = new MemoryStream();
BufferImage.Save(ImageStream, ImageFormat.Jpeg);
BufferImage.Dispose();
ImageData = ImageStream.ToArray();
ImageStream.Dispose();
//write the length of the image data...if zero, the deserialier won't load any image
DataStream.Write(ImageData.Length);
DataStream.Write(ImageData, 0, ImageData.Length);
}
else
{
DataStream.Write(ImageData.Length);
}
One reason of this is that the stream (MemoryStream or any other stream) that you have loaded the main image from has been disposed!
Such this case:
This is an extension method that converts a byte array to a bitmap, but using statement will dispose the memory stream, this will cause this error always:
public static Bitmap ToBitmap(this byte[] bytes)
{
if (bytes == null)
{
return null;
}
else
{
using(MemoryStream ms = new MemoryStream(bytes))
{
return new Bitmap(ms);
}
}
}
精彩评论