A generic error occurred in GDI+ exception when trying to save image into MemoryStream

廉价感情. 提交于 2019-12-12 16:32:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!