Monday, July 26, 2010

Cropping an Image in .NETCF

I've seen some people ask how to crop an image in .NET Compact Framework in the community. Although the operation is pretty simple, I'll share a code snippet anyway.

public static Image Crop(Image image, Rectangle bounds)
{
    Image newImage = new Bitmap(bounds.Width, bounds.Height);
 
    using (Graphics g = Graphics.FromImage(newImage))
        g.DrawImage(image, 
                    new Rectangle(0, 0, newImage.Width, newImage.Height), 
                    bounds, 
                    GraphicsUnit.Pixel);
 
    return newImage;
 
}

What the code above does is to create a new image and draw part of the source image specified in the bounds to the new image.

No comments: