Crop Images in C#

Image editing is quite common these days and in various cases, we need to manipulate the images to get the desired results. As a programmer, there could be a case for you to implement the image editing features from within the applications you are building. Recently, we have covered how to resize, rotate and flip images programmatically. Today, we are going to show you how to crop images using C# in your .NET applications. We will discuss how to perform image cropping using shift values or with a rectangle.

C# API to Crop Images - Free Download

For image cropping in C#, we will use Aspose.Imaging for .NET. It is a feature-rich API to seamlessly manipulate the images of popular formats. You can download the API or install it into your .NET applications using NuGet.

PM> Install-Package Aspose.Imaging

Crop Images in C#

Aspose.Imaging for .NET provides two ways to crop an image. In the first method, we need to provide left, right, top and bottom shift values. Whereas, in the second method, we define a rectangle to crop a certain area of an image.

In the following sections, we will demonstrate how to use both of the above-mentioned methods to crop images in C#.

Crop Images with Shift Values in C#

The following are the steps for cropping an image using shift values in C#.

  • First, load the image into a RasterImage object using Image.Load() method.
  • Cache the image for the better performance.
  • Define left, right, top and bottom shift values.
  • Pass the shift values to RasterImage.Crop() method to crop the image.
  • Save the cropped image using RasterImage.Save() method.

The following code sample shows how to crop an image in C#.

The following is the input image that we used for cropping.

crop image in C#

Below is the resultant cropped image.

image cropping in C#

C# Image Cropping using Rectangle

You can also define a rectangle to crop the desired area of an image. The following steps demonstrate image cropping with a rectangle in C#.

The following code sample shows how to perform image cropping with a rectangle in C#.

Imaging Cropping API for C# - Get a Free License

You can get a free temporary license and crop images without evaluation limitations.

Build Your Image Cropping Application

In this article, you have learned how to crop images in C#. We have demonstrated a couple of ways to crop an image using shift values or with a rectangle. Now, you can easily build your image cropping application or enhance the existing application’s image editing capabilities. To explore more about the C# image editing API, you can visit the documentation. Also, you can share your queries with us via our forum.

See Also