Reading a given rectangle from an image with ImageIO

Use the method setSourceRegion, defined in ImageReadParam and pass it to your reader. This example reads a given rectangle, specified by top x,y and width, height and creates a new image.

import javax.imageio.metadata.*; 
import javax.imageio.event.*;
import javax.imageio.*;
import java.awt.image.*; 
import java.util.*;
import java.awt.*;
public class Main 
   public static void main(String []args) throws Exception {
      if (args.length != 5 || !args[0].endsWith(".jpg")) {
         System.out.println("Usage: java Main image.jpg x y w h");
      int x = Integer.parseInt(args[1]);
      int y = Integer.parseInt(args[2]);
      int w = Integer.parseInt(args[3]);
      int h = Integer.parseInt(args[4]);
      Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
      ImageReader reader = (ImageReader);
      Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter);
      ImageInputStream iis = ImageIO.createImageInputStream(new File(args[0]));
      reader.setInput(iis, true);
      ImageReadParam param = reader.getDefaultReadParam();
      param.setSourceRegion(new Rectangle(x, y, w, h));
      BufferedImage bi =, param);
      String jpgFile = args[0].substring(0, args[0].length()-4) + "_new.jpg";
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(jpgFile));