Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java, Web
Expertise: Intermediate
Oct 11, 2002

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, String
saveAsFileName, 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 <fileName>
<output_file_name> <w> <h>");
			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
Santosh Sharan
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date