Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created September 20, 2022 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/f0d22423bdd8384b4ac6dededac1e8cf to your computer and use it in GitHub Desktop.
Save aspose-com-gists/f0d22423bdd8384b4ac6dededac1e8cf to your computer and use it in GitHub Desktop.
Crop Images Programmatically in C#
// Load the image.
using (RasterImage rasterImage = (RasterImage)Image.Load("image.png"))
{
// Before cropping, the image should be cached for better performance.
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Create an instance of Rectangle class with desired size and crop the image.
Rectangle rectangle = new Rectangle(20, 20, 20, 20);
rasterImage.Crop(rectangle);
// Save cropped image.
rasterImage.Save("cropped.png");
}
// Load the image to be cropped.
using (RasterImage rasterImage = (RasterImage)Image.Load("image.png"))
{
// 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 = 50;
int bottomShift = 50;
// Based on the shift values, apply the cropping on image. Crop method will shift the image bounds toward the center of image.
rasterImage.Crop(leftShift, rightShift, topShift, bottomShift);
// Save cropped image.
rasterImage.Save("cropped.png");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment