[英]Saving image: A generic error occurred in GDI+. (vb.net)
我需要在從OFD打開后保存圖像。 這是我的代碼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
在Image.FromFile(File).Save("C:\\Users\\Jonathan\\Desktop\\e\\tmp.png", Imaging.ImageFormat.png)
這一行上,它出現了錯誤。
(注意:應用程序將建立在這個只是我的第一個代碼,它將需要保存而不是復制)
我檢查兩件事:
打開或保存圖像會鎖定文件。 覆蓋此文件需要首先在持有鎖的Image對象上調用Dispose()。
我真的不了解你的代碼,但你必須這樣做:
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
Using語句確保處理img對象並釋放文件鎖。
圖像放鎖。
例如,我使用此緩沖區圖像保存到內存流中。
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);
}
這樣做的一個原因是您已經處理了從主圖像加載的流(MemoryStream或任何其他流)!
這樣的情況:
這是一個將字節數組轉換為位圖的擴展方法,但using語句將處理內存流,這將始終導致此錯誤:
public static Bitmap ToBitmap(this byte[] bytes)
{
if (bytes == null)
{
return null;
}
else
{
using(MemoryStream ms = new MemoryStream(bytes))
{
return new Bitmap(ms);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.