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.

Main.java:

import com.sun.image.codec.jpeg.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
 
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");
         System.exit(1);
      } 
 
      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.");
         }
      }
 
      System.exit(1);
   }
 
   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);
      g2d.dispose();
 
      FileOutputStream fos = new FileOutputStream(filename);
      if (filename.endsWith(".jpg")) {
         JPGWrite(scaledBi, fos);
      }
      fos.close();
   }
 
   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), 
                                           BufferedImage.TYPE_INT_RGB); 
 
      // copy the original image
      Graphics g = bi.createGraphics();
    
      g.drawImage(image, 0, 0, null);
      g.dispose();
 
      return bi;
   }
}