Generate Thumbnails Out of a Larger Image

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

See also  Is Machine Learning Automating Creativity in Graphic Design?

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist