Marc
Marc

Reputation: 6771

Crop a bitmap and expand the size if necessary

I want to crop a bitmap with this function but the bitmap could be smaller then the crop area so I want to get the bitmap bigger in that case.

As example I have a bitmap which is 200x250 and if I use the CropBitmap method with 250x250 I get an out of memory error. It should return a bitmap with 250x250 where the missing left 50px are filled with white.

How can I achieve that?

public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
{
    var rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);

    if(bitmap.Width < cropWidth || bitmap.Height < cropHeight)
    {
        // what now?
    }

    return bitmap.Clone(rect, bitmap.PixelFormat);
}

Upvotes: 3

Views: 1773

Answers (1)

Stephan
Stephan

Reputation: 4247

Create a new Bitmap with the appropriate size. Then get a System.Drawing.Graphics and use it to create the white area and to insert the source image. Something like this:

    if (bitmap.Width < cropWidth && bitmap.Height < cropHeight)
    {
        Bitmap newImage = new Bitmap(cropWidth, cropHeight, bitmap.PixelFormat);
        using (Graphics g = Graphics.FromImage(newImage))
        {
            // fill target image with white color
            g.FillRectangle(Brushes.White, 0, 0, cropWidth, cropHeight);

            // place source image inside the target image
            var dstX = cropWidth - bitmap.Width;
            var dstY = cropHeight - bitmap.Height;
            g.DrawImage(bitmap, dstX, dstY);
        }
        return newImage;
    }

Note, that I replaced the || in the outer if expression with &&. To make it work with ||, you have to calculate the source region and use another overload of Graphics.DrawImage

Upvotes: 4

Related Questions