How to crop an image

How to crop an image

         You can select between two types of possible cropping: either indicate new image boundaries by shifts from the sides of the image, i.e. 10 px for left, right top and bottom shifts or create a rectangle with the desired size and use it for image cropping.

Crop by shifts

         The example below makes an image Crop by shifts on 10px from each image side:

using Aspose.Imaging;
using System.IO;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
// Load an existing image into an instance of RasterImage class
using (RasterImage rasterImage = (RasterImage)Image.Load(dataDir + "template.jpg"))
{
// Before cropping, the image should be cached for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Define shift values for all four sides
int leftShift = 10;
int rightShift = 10;
int topShift = 10;
int bottomShift = 10;
// Based on the shift values, apply the cropping on image Crop method will shift the image bounds toward the center of image and Save the results to disk
rasterImage.Crop(leftShift, rightShift, topShift, bottomShift);
rasterImage.Save(dataDir + "result.jpg");
}
File.Delete(dataDir + "result.jpg");

Crop by rectangle

         In this example, we create a square with a side length of 20 px and then Crop by rectangle the photo to this area from the original picture.

using Aspose.Imaging;
using System.IO;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
// Load an existing image into an instance of RasterImage class
using (RasterImage rasterImage = (RasterImage)Image.Load(dataDir + "template.jpg"))
{
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Create an instance of Rectangle class with desired size, Perform the crop operation on object of Rectangle class and Save the results to disk
Rectangle rectangle = new Rectangle(20, 20, 20, 20);
rasterImage.Crop(rectangle);
rasterImage.Save(dataDir + "result.jpg");
}
File.Delete(dataDir + "result.jpg");