A generic error occurred in GDI+ exception when trying to save image into MemoryStream
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();
SurveyDia开发者_如何学编程grampictureBox.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+.
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;
}
}
精彩评论