尝试将图像保存到MemoryStream时在GDI +异常中发生一般错误 [英] A generic error occurred in GDI+ exception when trying to save image into MemoryStream
问题描述
我正在使用C#Windows窗体.
I am using C# windows form.
我的代码:
private void Openbutton_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
SurveyDiagrampictureBox.Image = Bitmap.FromFile(openFileDialog.FileName);
MemoryStream memoryStream = new MemoryStream();
SurveyDiagrampictureBox.Image.Save(memoryStream, ImageFormat.Jpeg);
SurveyDiagram = memoryStream.GetBuffer();
}
}
它并不总是发生,单步执行到此行时会抛出异常:SurveyDiagrampictureBox.Image.Save(memoryStream, ImageFormat.Jpeg);
It doesn't always occur, the exception throws when stepping to this line : SurveyDiagrampictureBox.Image.Save(memoryStream, ImageFormat.Jpeg);
异常消息:
类型的未处理异常 "System.Runtime.InteropServices.ExternalException"发生在 System.Drawing.dll
An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll
其他信息:GDI +中发生了一般性错误.
Additional information: A generic error occurred in GDI+.
推荐答案
GDI +位图不是线程安全的,因此这些错误通常来自在多个线程上访问的图像.似乎可能在这里发生(例如,PictureBox呈现图像,并且图像保存在按钮单击处理程序线程中).
GDI+ Bitmaps are not thread-safe, so often these errors arrive from the image being accessed on multiple threads. It seems like that could be occurring here (e.g. the PictureBox rendering the image and the image being saved on your button click handler thread).
完成保存操作后,如何将位图分配给PictureBox?
What about assigning the Bitmap to the PictureBox after completing the saving operations?
private void Openbutton_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
Image img = Bitmap.FromFile(openFileDialog.FileName);
MemoryStream memoryStream = new MemoryStream();
img.Save(memoryStream, ImageFormat.Jpeg);
SurveyDiagram = memoryStream.GetBuffer();
SurveyDiagrampictureBox.Image = img;
}
}
这篇关于尝试将图像保存到MemoryStream时在GDI +异常中发生一般错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!