views:

60

answers:

2

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.

A: 

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.

Michael Petrotta
Thanks for your response this answer and the other helped me resolve the problem, was getting all images including the temp thumbnail... infinite loop. Which lead me to your answer eventually the the image became 15x15 and the rect went out of bounds, cheers :)
Daniel Draper
A: 

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.

rob waminal