In the Java programming language, we need some classes to crop an image. So these classes are as follows:
1. To read and write an image file we have to import the File class. This class represents file and directory path names in general.
import java.io.File
2. To handle errors we use the IOException class.
import java.io.IOException
3. To hold the image we create the BufferedImage object for that we use BufferedImage class. This object is used to store an image in RAM.
import java.awt.image.BufferedImage
4. To perform the image read-write operation we will import the ImageIO class. This class has static methods to read and write an image.
import javax.imageio.ImageIO
Approach:
- Change dimensions of the image
- Using some in-built methods of BufferedImage class and Color c
Example:
Java
// Java Program to Crop Image Using BufferedImage Class // Importing required packages import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; // Main class public class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Reading original image from local path by // creating an object of BufferedImage class BufferedImage originalImg = ImageIO.read( new File( "D:/test/Image.jpeg" )); // Fetching and printing alongside the // dimensions of original image using getWidth() // and getHeight() methods System.out.println( "Original Image Dimension: " + originalImg.getWidth() + "x" + originalImg.getHeight()); // Creating a subimage of given dimensions BufferedImage SubImg = originalImg.getSubimage( 50 , 50 , 50 , 50 ); // Printing Dimensions of new image created System.out.println( "Cropped Image Dimension: " + SubImg.getWidth() + "x" + SubImg.getHeight()); // Creating new file for cropped image by // creating an object of File class File outputfile = new File( "D:/test/ImageCropped.jpeg" ); // Writing image in new file created ImageIO.write(SubImg, "png" , outputfile); // Display message on console representing // proper execution of program System.out.println( "Cropped Image created successfully" ); } // Catch block to handle the exceptions catch (IOException e) { // Print the exception along with line number // using printStackTrace() method e.printStackTrace(); } } } |
Output:
Cropped Image created successfully
Also, after executing the program console will show an executed message and a new cropped image will be created at the path entered which is shown below: