我正在尝试绘制图像并使用鼠标单击事件保存它。我添加了一个按钮来撤消上一次绘制操作。我正在通过鼠标单击事件加载先前保存的图像来执行此操作。我这里有个代码。我将展示我在代码中的注释中获得异常的部分:
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
}按钮下的代码为:
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.Load(string.Format("{0}.Bmp",textBox2.Text));
}在我的程序中,我尝试先保存图像,然后再绘制它。当我点击按钮时,它正在工作&加载图像,但当我再次尝试绘制它时,我得到了异常。请在我需要更改代码的地方提供帮助。
发布于 2011-06-29 00:20:10
问题是,当文件正由pictureBox1.Image对象使用时,您正在尝试将图像保存到文件中。
要模拟问题,请执行以下操作:
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中以进行撤消,而不是使用相同的图像文件来保持图像的先前状态以供撤消。
然而,要实现强大的多重撤销/重做,是一个很好的例子,适合您的情况。
https://stackoverflow.com/questions/6508146
复制相似问题