简体   繁体   中英

C# image manipulation using a console application throwing 'Out of Memory' Exception

I have a console application that successfully re-sizes an image while maintaining aspect ratio.

I now need to crop the image the code I am using is below:

using (var thumbnail = CropPicture(image, rectangle)) {
    EncoderParameters encParams = new EncoderParameters(1);
    encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)90);

    thumbnail.Save(destination, GetImageCodecInfo(image.RawFormat), encParams); 
}

public static Image CropPicture(Image source, Rectangle cropArea) {
    using (var bitmap = new Bitmap(source)) {
        return (Image)(bitmap.Clone(cropArea, source.PixelFormat));
    }
}

It seems to be throwing an Out of memory exception on the line

return (Image)(bitmap.Clone(cropArea, source.PixelFormat));

Any ideas what's going on? I think it's an open file can't be 100% sure.

instead of returning the Image inside the using why not create a reference before returning it inside the using statement.

public static Image CropPicture(Image source, Rectangle cropArea) {
    Bitmap retImg;
    using (var bitmap = new Bitmap(source)) {
        retImg = bitmap.Clone(cropArea, source.PixelFormat);
    }
    return (Image)regImg;
}

I'm not sure but it looks like the Bitmap is not disposed before you return the image.

According to the MSDN documentation, Bitmap.Clone(Rectangle, PixelFormat) can throw an OutOfMemoryException if the first parameter is "outside of the source bitmap bounds".

Verify the first parameter to Bitmap.Clone ; make sure that the rect is entirely within the bounds of the image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM