How to crop an image

How to crop an image

         To crop an image you can select between two cropping types: either indicate new image boundaries by shifts from the sides of the image, i.e. 10 px for left, right, top and bottom sides or select a rectangle with the appropriate sizes and use it for image cropping.

Crop by shifts

         The example below crop an image by utilizing the crop by shift method with size of 10px from each image side:

import aspose.pycore as aspycore
from aspose.imaging import RasterImage, Image, Rectangle
import os
if 'TEMPLATE_DIR' in os.environ:
templates_folder = os.environ['TEMPLATE_DIR']
else:
templates_folder = r"C:\Users\USER\Downloads\templates"
delete_output = 'SAVE_OUTPUT' not in os.environ
data_dir = templates_folder
# Load an existing image into an instance of RasterImage class
with aspycore.as_of(Image.load(os.path.join(data_dir, "template.jpg")), RasterImage) as raster_image:
# Before cropping, the image should be cached for better performance
if not raster_image.is_cached:
raster_image.cache_data()
# Define shift values for all four sides
left_shift = 10
right_shift = 10
top_shift = 10
bottom_shift = 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
raster_image.crop(left_shift, right_shift, top_shift, bottom_shift)
raster_image.save(os.path.join(data_dir, "result.jpg"))
if delete_output:
os.remove(os.path.join(data_dir, "result.jpg"))

Crop by rectangle

         In this example, we create a square with a side length of 20 px and then crop an image using crop by rectangle method applied this area to the original photo:

import aspose.pycore as aspycore
from aspose.imaging import RasterImage, Image, Rectangle
import os
if 'TEMPLATE_DIR' in os.environ:
templates_folder = os.environ['TEMPLATE_DIR']
else:
templates_folder = r"C:\Users\USER\Downloads\templates"
delete_output = 'SAVE_OUTPUT' not in os.environ
data_dir = templates_folder
# Load an existing image into an instance of RasterImage class
with aspycore.as_of(Image.load(os.path.join(data_dir, "template.jpg")), RasterImage) as raster_image:
if not raster_image.is_cached:
raster_image.cache_data()
# 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(20, 20, 20, 20)
raster_image.crop(rectangle)
raster_image.save(os.path.join(data_dir, "result.jpg"))
if delete_output:
os.remove(os.path.join(data_dir, "result.jpg"))