How to crop an image in Java

Hi guys, today we will learn how to crop an image in Java.

First of all, we should know what is cropping an image means? So cropping of an image means getting a sub-image from the original image.

There can be multiple ways to solve this issue as per one understanding.

In this tutorial, to crop an image in java, we will use some in-built method of BufferedImage class, specifically the getSubmage method of BufferedImage class.

Syntax of getSubimage method of BufferedImage class is:

public BufferedImage getSubimage(int X, int Y, int width, int height)

which returns a sub-image which will be decided by the rectangular region formed due to passed arguments. Description of four parameters is given below:

  1. X – It tells us the x-coordinate of the specified rectangular region on the upper-left corner.
  2. Y – It tells us the y-coordinate of the specified rectangular region on the upper-left corner.
  3. height – It specifies the height of the rectangular region.
  4. width – It specifies the width of the rectangular region.

How to crop an image: Java Code

import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

class Main{
public static void main(String []args){

  File imageFile = new File("/home/shivank/Downloads/image.jpeg");
  BufferedImage bufferedImage =null;
      bufferedImage =;
      BufferedImage image=bufferedImage.getSubimage(0,0,500,500);
      File pathFile = new File("/home/shivank/Downloads/image-crop.jpeg");
      ImageIO.write(image,"jpeg", pathFile);
  catch (IOException e) 


the input image is:

input image : Crop an image in Java

case 1: when X=0 & Y=0, output image will be:

Java image crop

case 2: when Y=200 & Y=300, the output image will be:

case 2 crop image using java

Please note that you have to give your own file path as I have given mine in line number 10 & 16. Also, you can take the value of X, Y, width & height at run time by user to add more dynamicity in your code.

Now, you have learned how to crop an image in java. Feel free to comment in case if you have any queries.

you may also read:

Plot the negative of an image in Java

Leave a Reply

Your email address will not be published. Required fields are marked *