【发布时间】:2016-04-27 05:04:04
【问题描述】:
我正在尝试使用 (x,y) 坐标、宽度和高度来裁剪 jpeg 文件,并将输出保存在同一位置(即替换)。我尝试了下面的代码,但它不起作用。
public void CropImage(int x, int y, int width, int height)
{
string image_path = @"C:\Users\Admin\Desktop\test.jpg";
var img = Image.FromFile(image_path);
Rectangle crop = new Rectangle(x, y, width, height);
Bitmap bmp = new Bitmap(crop.Width, crop.Height);
using (var gr = Graphics.FromImage(bmp))
{
gr.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), crop, GraphicsUnit.Pixel);
}
if (System.IO.File.Exists(image_path))
{
System.IO.File.Delete(image_path);
}
bmp.Save(image_path, ImageFormat.Jpeg);
}
这会产生如下错误:
在 mscorlib.dll 中发生了“System.IO.IOException”类型的异常,但未在用户代码中处理
附加信息:进程无法访问文件 'C:\Users\Admin\Desktop\test.jpg' 因为它正在被另一个人使用 过程。
当我添加 img.Dispose() 时,我没有收到上述错误,我可以保存它。但它会保存给定宽度和高度的空白图像。
谁能帮我解决这个问题?
【问题讨论】:
-
旧图像仍被您的代码阻止。您可以选择其他名称或阅读如何解除阻止的众多帖子中的一个。搜索“c# Save jpeg IOException”
-
@TaW,即使我给出了一条新路径,我也得到了一个具有给定宽度和高度的空白图像
-
它不应为空,除非您将其丢弃。不过请注意矩形的顺序!见here
-
@TaW 我试过
using这样保存 IOEcxeption 不会出现,它仍然无法正常工作。矩形的顺序是正确的
标签: c# image crop system.drawing