如何在c#中裁剪和保存jpeg图像文件

Jib*_*ran 2 c# system.drawing image crop

我正在尝试使用(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);
}
Run Code Online (Sandbox Code Playgroud)

这给出了如下错误:

mscorlib.dll中出现"System.IO.IOException"类型的异常,但未在用户代码中处理

附加信息:进程无法访问文件'C:\ Users\Admin\Desktop\test.jpg',因为它正由另一个进程使用.

当我添加时,img.Dispose()我没有得到上述错误,我可以保存它.但它保存具有给定宽度和高度的空白图像.

任何人都可以帮我解决这个问题吗?

Ale*_*rov 8

public void CropImage(int x, int y, int width, int height)
{
    string imagePath = @"C:\Users\Admin\Desktop\test.jpg";
    Bitmap croppedImage;

    // Here we capture the resource - image file.
    using (var originalImage = new Bitmap(imagePath))
    {
        Rectangle crop = new Rectangle(x, y, width, height);

        // Here we capture another resource.
        croppedImage = originalImage.Clone(crop, originalImage.PixelFormat);

    } // Here we release the original resource - bitmap in memory and file on disk.

    // At this point the file on disk already free - you can record to the same path.
    croppedImage.Save(imagePath, ImageFormat.Jpeg);

    // It is desirable release this resource too.
    croppedImage.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

  • @ J19 - 也许要裁剪的区域会出现在图像的白色部分? (2认同)