Home >Backend Development >C++ >How Can I Crop an Image Using C#?

How Can I Crop an Image Using C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-27 20:19:08336browse

How Can I Crop an Image Using C#?

Crop image using C#

Image cropping refers to removing the unwanted parts of the edges of the image. In C#, you can use the Bitmap class to implement image cropping. Here's a simple way to crop an image:

<code class="language-csharp">using System.Drawing;

private static Image CropImage(Image img, Rectangle cropArea)
{
   Bitmap bmpImage = new Bitmap(img);
   return bmpImage.Clone(cropArea, bmpImage.PixelFormat);
}</code>

Usage:

To crop an image, provide the original image and a Rectangle object that defines the cropping area. A Rectangle object specifies the left, top, width, and height of the area to be preserved. The CropImage method will return a new Image object containing the cropped part.

Example:

Consider the following usage:

<code class="language-csharp">Image originalImage = Image.FromFile("image.png");

Rectangle cropArea = new Rectangle(100, 100, 200, 300);
Image croppedImage = CropImage(originalImage, cropArea);</code>

In this example, a region of the original image starting at coordinates (100, 100) with a width of 200 pixels and a height of 300 pixels will be cropped, and the result will be stored in the croppedImage variable.

More resources:

For more detailed information and examples, please refer to the following resources:

The above is the detailed content of How Can I Crop an Image Using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn