This tip will take a jpeg image and turn it in to a thumbnail.

This program takes three parameters. The first is the name of the file you want to create the thumbnail out of(berry.jpeg). The second will be the name of the new thumbnail file(newberry.jpeg) and the last is the size you want the jpeg to be.

So once you compile and run the code, type the following on the command line.

java Thumbnail berry.jpeg newberry.jpeg 50

Now run the program and a new file will be create in the same directory as your program named newberry.jpeg.

Attached at the end of this tip is the berry.jpg file.

==========================================

import java.awt.Image;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
import javax.swing.ImageIcon;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

class Thumbnail {
public static void main(String[] args) {
createThumbnail(args[0], args[
1], Integer.parseInt(args[2]));
}

public static void createThumbnail(
String orig, String thumb, int maxDim) {
try {
// Get the image from a file.
Image inImage = new ImageIcon(
orig).getImage();

// Determine the scale.
double scale = (double)maxDim/(
double)inImage.getHeight(null);
if (inImage.getWidth(
null) > inImage.getHeight(null)) {
scale = (double)maxDim/(
double)inImage.getWidth(null);
}

// Determine size of new image.
//One of them
// should equal maxDim.
int scaledW = (int)(
scale*inImage.getWidth(null));
int scaledH = (int)(
scale*inImage.getHeight(null));

// Create an image buffer in
//which to paint on.
BufferedImage outImage =
new BufferedImage(scaledW, scaledH,
BufferedImage.TYPE_INT_RGB);

// Set the scale.
AffineTransform tx =
new AffineTransform();

// If the image is smaller than
//the desired image size,
// don't bother scaling.
if (scale < 1.0d) {
tx.scale(scale, scale);
}

// Paint image.
Graphics2D g2d =
outImage.createGraphics();
g2d.drawImage(inImage, tx, null);
g2d.dispose();

// JPEG-encode the image
//and write to file.
OutputStream os =
new FileOutputStream(thumb);
JPEGImageEncoder encoder =
JPEGCodec.createJPEGEncoder(os);
encoder.encode(outImage);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}

BERRY.JPEG (4.4 KB)