Search code examples
c#imagebitmapcrop

Invert Crop from (Cut hole into) Image


Everywhere I look online, I see people posting on how to successfully crop an image. However, I want to 'crop'/ clear a hole out of an image. I want to keep the original image, but crop out a rectangle

enter image description here

As you can see in the image above, I have "cropped" out the kittens face. I maintained the original image, but removed only part of it. I cannot figure out how to do that.


Solution

  • Assuming you want to replace the original pixel colors with transparency you run into a small problem: You can't draw or fill with transparency in GDI+.

    But you can use Graphics.Clear(Color.Transparent).

    To do that you restrict the region where the Graphics object will draw. Here we can use the simple cropping rectangle but you can clear more complex shapes using a GraphicsPath..

    Example using a bitmap bmp:

    using (Graphics g = Graphics.FromImage(bmp))
    {
        Rectangle crop = new Rectangle(222,222,55,55);
        g.SetClip(crop);
        g.Clear(Color.Transparent);
    }
    bmp.Save(somefilename, ImageFormat.Png);