尝试将图像保存到MemoryStream时,GDI +异常中发生了一般错误

时间:2011-10-08 04:02:21

标签: c# winforms bitmap gdi+ memorystream

我使用的是C#窗体。

我的代码:

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);

异常消息:

  

未处理的类型异常   发生'System.Runtime.InteropServices.ExternalException'   System.Drawing.dll程序

     

其他信息:GDI +中发生了一般性错误。

1 个答案:

答案 0 :(得分:1)

GDI +位图不是线程安全的,因此这些错误通常来自在多个线程上访问的图像。看起来这可能发生在这里(例如,PictureBox渲染图像,图像保存在按钮点击处理程序线程上)。

完成保存操作后,如何将Bitmap分配给PictureBox?

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;
        }
}