How to crop an image
How to crop an image
Image cropping supports two types of possible methods: either crop by defining new image boundaries by shifts from the sides of the image, for example, 10 px for left, right top and bottom shifts or to indicate a rectangle area to use for the image cropping.
Crop by shifts
Please see the example below which use the Crop method of the Java class RasterImage to crop the image by shifts on 10px from each side:
// The path to the documents directory. | |
String dataDir = "dataDir/jpeg/"; | |
// Load an existing image into an instance of RasterImage class | |
try (RasterImage rasterImage = (RasterImage)Image.load(dataDir + "aspose-logo.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 + "CroppingByShifts_out.jpg"); | |
} |
Crop by rectangle
This example shows how to create a rectangle area with a sides length of 20 px and then Crop by rectangle the selected area from the original picture:
// The path to the documents directory. | |
String dataDir = "dataDir/jpeg/"; | |
// Load an existing image into an instance of RasterImage class | |
try (RasterImage rasterImage = (RasterImage)Image.load(dataDir + "aspose-logo.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 + "CroppingByRectangle_out.jpg"); | |
} |