By popular demand – scaling images in Java for Lotus Connections

After blogging about how Lotus Connetions teaches you to scale images in Java the other day I was contacted by Lotus Support who really would like to see the code as customers were asking for such code. Mitch also forwarded me a response from Lotus Support where they referred to my blog post which I got a real kick out of… 🙂

So here’s the code. Thanks to the customer for allowing me to blog the code. Use to your hearts content but don’t blame me if it doesn’t work for you. The disclaimer is there for a reason.

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOError;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ScalePicture {

  public static void main(String[] args) {
    try {
      File f = new File("d:\images");
      File pictSrc = new File(f, "source_photo.jpg");
      File pictDest = new File(f, "destination_photo.jpg");
      if (pictDest.exists()) {
        System.out.println("deleting...");
        pictDest.delete();
      }

      // scale image
      BufferedImage img = scaleImage(pictSrc);

      // write to target image
      ImageIO.write(img, "jpg", pictDest);

    } catch (Throwable t) {
      t.printStackTrace();
    }
  }

  private static BufferedImage scaleImage(File source)
    throws IOException {
    // declarations
    final int width = 115;
    final int height = 115;

    // read source image
    BufferedImage imgSrc = ImageIO.read(source);

    // calculate scale factor
    double scaleFactor = (double)imgSrc.getWidth() /
      (double)width;

    // scale image
    BufferedImage imgScaled = new BufferedImage((int)
      (scaleFactor * 100), height,
      BufferedImage.TYPE_INT_RGB);
    AffineTransform transform = AffineTransform.
      getScaleInstance(scaleFactor, scaleFactor);
    Graphics2D g = imgScaled.createGraphics();
    g.drawRenderedImage(imgSrc, transform);
    g.dispose();

    // create new target image in correct size
    // with white background
    BufferedImage imgResized = new BufferedImage(width,
      height,
      BufferedImage.TYPE_INT_RGB);
    g = imgResized.createGraphics();
    g.setBackground(Color.WHITE);
    g.fillRect(0, 0, width, height);

    // calculate offset for scaled image on new image
    int xoffset = (int)((double)(width - imgScaled.getWidth()) /
      (double)2);

    // draw scaled image on new image
    g.drawImage(imgScaled, xoffset, 0, null);
    g.dispose();

    // return new image
    return imgResized;
  }

}