문제

Im trying to save a file that i am using im getting a GDI+ error because im trying to save over the source file im using. Any solutions?

Example:

private void Form1_Load(object sender, EventArgs e)
{
   Bitmap sourceImage = new Bitmap("images/sourceImage.jpg");
   sourceImage = CropBitmap(sourceImage, 0, 0, sourceImage.Width, 50);
   sourceImage.Save("images/sourceImage.jpg", ImageFormat.Jpeg);
}

public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
{
    Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
    Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
    return cropped;
}
도움이 되었습니까?

해결책

See the documentation for this constructor. Specifically the section that reads:

The file remains locked until the Bitmap is disposed.

You must dispose the sourceImage before saving a new one. So, use different variables:

var sourceImage = new Bitmap("images/sourceImage.jpg");
var croppedImage = CropBitmap(sourceImage, 0, 0, sourceImage.Width, 50);
sourceImage.Dispose();
croppedImage.Save("images/sourceImage.jpg", ImageFormat.Jpeg);
croppedImage.Dispose();

다른 팁

When you replace sourceImage with the reference from CropBitmap, the original file is still open. You will have to Dispose of it after reading it from the file, open a new Bitmap and save it overwriting the existing one.

private void Form1_Load(object sender, EventArgs e)
{
    Bitmap sourceImage = new Bitmap("images/sourceImage.jpg");
    Bitmap targetImage = CropBitmap(sourceImage, 0, 0, sourceImage.Width, 50);
    sourceImage.Dispose();
    targetImage.Save("images/sourceImage.jpg", ImageFormat.Jpeg);
}

MSDN Bitmap documentation

The file remains locked until the Bitmap is disposed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top