Read a JPG image, rescale it, and write it back to disk

This example shows how to read, scale and rewrite all jpeg images from the current directory.

import com.sun.image.codec.jpeg.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
public class Main
   private final static float JPG_QUALITY = 1f;   // keep original JPEG quality
   public static void main(String []args) throws Exception {
      if (args.length != 2) {
         System.err.println("Usage: java Main scalex scaley");
         System.err.println("Scales all .jpg and .gif images to scalex, scaley");
      int scalex = Integer.parseInt(args[0]);
      int scaley = Integer.parseInt(args[1]);
      File f = new File(".");
      String[] fileList = f.list();
      for (int i=0; i<fileList.length; i++) {
         if (fileList[i].endsWith(".jpg")) {
            System.out.print("Rescaling " + fileList[i] + "...");  
            readScaleWrite(fileList[i], scalex, scaley);
            System.out.println(" done.");
   public static void readScaleWrite(String filename, int scalex, int scaley) 
                                                           throws Exception {
      Image img = new javax.swing.ImageIcon(filename).getImage(); 
      BufferedImage bi = toBufferedImage(img);
      BufferedImage scaledBi = new BufferedImage(scalex, scaley, bi.getType());
      AffineTransform at = new AffineTransform();
      at.scale((double) scalex / bi.getWidth(), (double) scaley / bi.getHeight());
      Graphics2D g2d = scaledBi.createGraphics();
      g2d.drawImage(bi, at, null);
      FileOutputStream fos = new FileOutputStream(filename);
      if (filename.endsWith(".jpg")) {
         JPGWrite(scaledBi, fos);
   public static void JPGWrite(BufferedImage bi, OutputStream out) throws IOException {
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
      param.setQuality(JPG_QUALITY, true);
      encoder.encode(bi, param);
   public static BufferedImage toBufferedImage(Image image) {
      BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), 
      // copy the original image
      Graphics g = bi.createGraphics();
      g.drawImage(image, 0, 0, null);
      return bi;