Java Program to Crop Image Using BufferedImage Class
Last Updated :
17 Oct, 2022
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
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class GFG {
public static void main(String[] args)
{
try {
BufferedImage originalImg = ImageIO.read(
new File( "D:/test/Image.jpeg" ));
System.out.println( "Original Image Dimension: "
+ originalImg.getWidth()
+ "x"
+ originalImg.getHeight());
BufferedImage SubImg
= originalImg.getSubimage( 50 , 50 , 50 , 50 );
System.out.println( "Cropped Image Dimension: "
+ SubImg.getWidth() + "x"
+ SubImg.getHeight());
File outputfile
= new File( "D:/test/ImageCropped.jpeg" );
ImageIO.write(SubImg, "png" , outputfile);
System.out.println(
"Cropped Image created successfully" );
}
catch (IOException e) {
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...