Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

How to crop an image in Java

37 sec read

Crop an image in java

In this article, I will show you how to crop an image in Java using just ImageIO or JDeli.

Crop an image in Java with:

ImageIO

  1. Load the image file using Java ImageIO (which is built into Java)

    BufferedImage image = ImageIO.read(new File("C:\\path\\to\\kitten.jpg"));

  2. Get a cropped version (x, y, width, height) (0,0 is top left corner)

    BufferedImage crop = image.getSubimage(0,0, 100, 100);

  3. Save the image back to a File

    ImageIO.write(crop, "JPEG", new File("C:\\path\\to\\picture.jpeg"));

Note it is important to save the image before applying any other changes as the BufferedImage object is shared between the original and new crop object.

JDeli

  1. Create a Crop ImageOperation in JDeli (here is how to setup JDeli)

    ImageProcessingOperations imageOps = new ImageProcessingOperations();
    imageOps.crop(new Rectangle(0, 0, 100, 100)); //you can add other Operations as well

  2. Get a cropped version (x, y, width, height) (0,0 is top left corner)

    JDeli.convert(new File("C:\\path\\to\\picture.jpeg"), new File("C:\\path\\to\\crop.jpeg"), imageOps);

And that is all you need to do!!!



Why do developers choose JDeli over free alternatives?

  1. Works with newer image formats such as AVIF, HEIC, JPEG XL, WEBP (AVIF next release) that are not supported in Java.
  2. Better support than alternatives for JPEG, PNG, TIFF.
  3. Process images up to 3x faster than ImageIO and other Java image libraries.
  4. Prevent JVM crashes caused by native code in other image libraries such as ImageIO.
  5. Image security as JDeli processes images on your servers with no calls to any external system or third party library.

Are you a Java Developer working with Image files?

Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

What is JPEG XL?

Nadir
55 sec read

What is JBIG2?

JBIG2 is a lossless and lossy compression standard for bi-level images like scanned documents, offering high compression ratios by identifying and encoding similar shapes...
chika
47 sec read