下面的代码在一张图象上写文字,但如果oImg.Save一句文件名与源文件名相同,保存时就报出例外错误,有什么简便的办法解决?
private void button1_Click(object sender, System.EventArgs e)
{
System.Drawing.Image oImg=System.Drawing.Image.FromFile(@"C:\1.jpg");
Graphics g=Graphics.FromImage(oImg);
g.InterpolationMode=InterpolationMode.HighQualityBilinear;
SolidBrush brush=new SolidBrush(Color.Red);
PointF P=new PointF(100,100);
Font f=new Font(this.Font.Name,40);
g.DrawString("Hello, world!",f,brush,P);
oImg.Save(@"C:\1.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
MessageBox.Show("OK");
f.Dispose();
g.Dispose();
oImg.Dispose();
}
private void button1_Click(object sender, System.EventArgs e)
{
System.Drawing.Image oImg=System.Drawing.Image.FromFile(@"C:\1.jpg");
Graphics g=Graphics.FromImage(oImg);
g.InterpolationMode=InterpolationMode.HighQualityBilinear;
SolidBrush brush=new SolidBrush(Color.Red);
PointF P=new PointF(100,100);
Font f=new Font(this.Font.Name,40);
g.DrawString("Hello, world!",f,brush,P);
oImg.Save(@"C:\1.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
MessageBox.Show("OK");
f.Dispose();
g.Dispose();
oImg.Dispose();
}
用SaveFileDialog(),来获得需要保存的文件名和路径或者你这样子做:
if (File.Exists(strFileName)) //判断文件是否存在
{
do
{
strFileName = strFileName.Replace(".", "_1.");
} while (File.Exists(strFileName));
bmpNew.Save(strFileName, imageType);
}
如果要删除,一定要把调用老图的Graphics类显示释放资源,不然还是无法删除的。因为内存还在使用这个文件。
System.Drawing.Bitmap map = new Bitmap(oImg);
oImg.Dispose();
Graphics g = Graphics.FromImage(map);
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
SolidBrush brush = new SolidBrush(Color.Red);
PointF P = new PointF(100, 100);
Font f = new Font(this.Font.Name, 40);
g.DrawString("Hello, world!", f, brush, P);
map.Save(@"C:\1.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
MessageBox.Show("OK");
f.Dispose();
g.Dispose();
不允许将图像保存到构造该图像的文件,这样会引发异常。