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.

Main.java:

import javax.imageio.metadata.*; 
import javax.imageio.stream.*;
import javax.imageio.event.*;
import javax.imageio.*;
 
import java.awt.image.*; 
import java.util.*;
import java.awt.*;
import java.io.*;
  
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");
         System.exit(1);
      }
 
      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) readers.next();
 
      Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter) writers.next();
 
      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 = reader.read(0, param);
  
      String jpgFile = args[0].substring(0, args[0].length()-4) + "_new.jpg";
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(jpgFile));
      writer.setOutput(ios);
      writer.write(bi);
   }
}