【问题标题】:Saving jpeg - The process cannot access the file because it is being used by another process?保存 jpeg - 进程无法访问该文件,因为它正被另一个进程使用?
【发布时间】: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


【解决方案1】:
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();
}

【讨论】:

  • 这也保存了一个给定高度和宽度的空白 jpeg 文件。我在图像路径中给出了完整路径,例如`@"C:\Users\Admin\Desktop\test.jpg`
  • 我不知道为什么,它给了我一个空白的jpeg文件
  • @J19 - 可能要裁剪的区域位于图像的白色部分?
  • 是的,这就是问题所在.. 非常感谢.. 简单的错误,但我发现很难弄清楚。
  • 裁剪后的图片画质很差。。有什么办法可以在不丢失画质的情况下裁剪图片?
猜你喜欢
  • 2016-04-18
  • 2010-12-10
相关资源
最近更新 更多