问题
I am using C# windows form.
My code :
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();
}
}
It doesn't always occur, the exception throws when stepping to this line : SurveyDiagrampictureBox.Image.Save(memoryStream, ImageFormat.Jpeg);
Exception message :
An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll
Additional information: A generic error occurred in GDI+.
回答1:
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).
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;
}
}
来源:https://stackoverflow.com/questions/7694741/a-generic-error-occurred-in-gdi-exception-when-trying-to-save-image-into-memory