質問

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