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 200×250 and if I use the CropBitmap method with 250×250 I get an out of memory error. It should return a bitmap with 250×250 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);
}
Create a new Bitmap with the appropriate size. Then get a
System.Drawing.Graphicsand use it to create the white area and to insert the source image. Something like this:Note, that I replaced the
||in the outerifexpression with&&. To make it work with||, you have to calculate the source region and use another overload of Graphics.DrawImage