Generate Thumbnails Out of a Larger Image

This is useful in a Web-based Photo Gallery kind of application, where you need to automatically generate multiple sizes of the same image.

 class ThumbnailGenerator {    public void generateThumbnail (String origFile, String saveAsFileName){		Image image = new ImageIcon(origFile).getImage();		// Reduces to 1/4th size.		int h = image.getHeight(null)/4;    	int w = image.getWidth(null)/4;    	reallyGenerateThumbnail(image, saveAsFileName, w, h);    }    public void generateThumbnail (String origFile, String saveAsFileName,int w, int h) {		Image image = new ImageIcon(origFile).getImage();    	reallyGenerateThumbnail(image, saveAsFileName, w, h);    }    public void reallyGenerateThumbnail(Image image, StringsaveAsFileName, int w, int h){        try{			BufferedImage buf = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB);			Graphics g = buf.getGraphics();			g.drawImage(image, 0, 0, w, h, null);			g.dispose();			OutputStream stream = new FileOutputStream(saveAsFileName);			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(stream);			encoder.encode(buf);			stream.close();			System.exit(0);		}catch(Exception e){			System.out.println(" Exception : You're evil ! You Broke My Code !!! "+ e.getMessage());		}	}    public static void main(String[] args) {        if (( args.length < 2 ) || (args.length > 4))        {			System.out.println(" usage .. ThumbnailGenerator   ");			System.exit(0);		}		ThumbnailGenerator th = new ThumbnailGenerator();		if ( args.length < 3)		th.generateThumbnail(args[0], args[1]);    	else		th.generateThumbnail(args[0], args[1], Integer.parseInt(args[2]),Integer.parseInt(args[3]));    }}

The code uses the com.sun.image.codec.jpeg package of JDK1.2

The program accepts a JPG or a GIF image file and generates a thumbnail of type JPEG. It also takes two additional/optional parameters

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: