保存图像,在GDI发生一般性错误+ [英] Saving An image,A generic error occurred in GDI+
问题描述
我得到一个
在GDI +
异常,当我打电话 img.Save(路径,jpegCodec,encoderParams);
结果
这里是所有的代码:
exception when I call img.Save(path, jpegCodec, encoderParams);
here is all of the code :
private Image img;
private void button1_Click(object sender, EventArgs e)
{
this.img = Image.FromFile(@"path");
pictureBox1.Image = img;
if (img.Height < pictureBox1.Height && img.Width < pictureBox1.Width)
{
this.pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
}
Graphics g = Graphics.FromImage(img);
Font font=new Font("Arial",16);
SolidBrush brush = new SolidBrush(Color.Black);
brush.Color = Color.FromArgb(255, 0, 0, 255);
g.DrawString("myName", font, brush, img.Width - 178, img.Height-105);
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(img);
saveJpeg(@"path", bitmap, 85L);
}
private void saveJpeg(string path, Bitmap img, long quality)
{
// Encoder parameter for image quality
EncoderParameter qualityParam =new EncoderParameter(Encoder.Quality, quality);
// Jpeg image codec
ImageCodecInfo jpegCodec = getEncoderInfo("image/jpeg");
if (jpegCodec == null)
return;
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
//img.Save(path, jpegCodec, encoderParams);
img.Save(path, jpegCodec, encoderParams);
}
private ImageCodecInfo getEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
你能帮我吗?
Would you help me?
推荐答案
只要图像对象存在被从文件中加载图像创建的,该文件正在使用中。而文件正在使用无法保存图像使用相同的名称。
As long as the image object exists that was created by loading the image from the file, the file is in use. You can't save an image with the same name while the file is in use.
而不是使用 Image.FromFile
加载图像,打开一个文件流,并使用 Image.FromStream
来创建图像,然后关闭文件流。这样的文件不再使用,你可以取代它。
Instead of using Image.FromFile
to load the image, open a file stream and use Image.FromStream
to create the image, then close the file stream. That way the file is no longer in use, and you can replace it.
这篇关于保存图像,在GDI发生一般性错误+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!