首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取System.Runtime.InteropServices.ExternalException!

获取System.Runtime.InteropServices.ExternalException!
EN

Stack Overflow用户
提问于 2011-06-28 22:33:06
回答 1查看 1K关注 0票数 1

我正在尝试绘制图像并使用鼠标单击事件保存它。我添加了一个按钮来撤消上一次绘制操作。我正在通过鼠标单击事件加载先前保存的图像来执行此操作。我这里有个代码。我将展示我在代码中的注释中获得异常的部分:

代码语言:javascript
复制
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
    rect.Width = 0;
    rect.Height = 0;
    pictureBox1.Invalidate();

    pictureBox1.Image.Save(String.Format("{0}.Bmp",textBox2.Text )); //getting exception here!! 

    int radius = 10; //Set the number of pixel you want to use here

    //Calculate the numbers based on radius
    int x0 = Math.Max(e.X - (radius / 2), 0),
        y0 = Math.Max(e.Y - (radius / 2), 0),
        x1 = Math.Min(e.X + (radius / 2), pictureBox1.Width),
        y1 = Math.Min(e.Y + (radius / 2), pictureBox1.Height);

    Bitmap bm = pictureBox1.Image as Bitmap; //Get the bitmap (assuming it is stored that way)
    for (int ix = x0; ix < x1; ix++)
    {
        for (int iy = y0; iy < y1; iy++)
        {
            bm.SetPixel(ix, iy, Color.Black); //Change the pixel color, maybe should be relative to bitmap
        }
    }
    pictureBox1.Refresh(); //Force refresh
}

按钮下的代码为:

代码语言:javascript
复制
private void button2_Click(object sender, EventArgs e)
{
    pictureBox1.Load(string.Format("{0}.Bmp",textBox2.Text));
}

在我的程序中,我尝试先保存图像,然后再绘制它。当我点击按钮时,它正在工作&加载图像,但当我再次尝试绘制它时,我得到了异常。请在我需要更改代码的地方提供帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-29 00:20:10

问题是,当文件正由pictureBox1.Image对象使用时,您正在尝试将图像保存到文件中。

要模拟问题,请执行以下操作:

代码语言:javascript
复制
string imageFilePath = string.Format("{0}.Bmp",textBox2.Text);

pictureBox1.Image.Save(imageFilePath);
pictureBox1.Load(imageFilePath);
pictureBox1.Image.Save(imageFilePath);//ExternalException will be thrown here.

您可以声明一个私有Image字段,并在每次加载时将图像加载到该字段中,然后将图像保存到该字段中,而不是将其保存到pictureBox1.Image中以进行撤消,而不是使用相同的图像文件来保持图像的先前状态以供撤消。

然而,要实现强大的多重撤销/重做,是一个很好的例子,适合您的情况。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6508146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档