E-commerce sites and other systems, there are a large number of pictures, from the loading speed and traffic angle, will use more thumbnails.
1 , create thumbnail source code for pictures
Package com.daily;
Import Java.awt.Container;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import Java.awt.MediaTracker;
Import java.awt.RenderingHints;
Import Java.awt.Toolkit;
Import Java.awt.image.BufferedImage;
Import Java.io.BufferedOutputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Com.sun.image.codec.jpeg.JPEGCodec;
Import Com.sun.image.codec.jpeg.JPEGEncodeParam;
Import Com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* generate thumbnail images
* @author Fan Fangming
*/
public class Easythumbnail {
Private Voidcreatethumbnail (String filename, int thumbwidth,
intthumbheight, int quality, String outfilename)
Throwsinterruptedexception, FileNotFoundException, IOException {
LoadImage from filename
Image image= Toolkit.getdefaulttoolkit (). getImage (filename);
Mediatrackermediatracker = new Mediatracker (new Container ());
Mediatracker.addimage (image,0);
Mediatracker.waitforid (0);
Determinethumbnail size from WIDTH and HEIGHT
Doublethumbratio = (double) thumbwidth/(double) thumbheight;
Intimagewidth = Image.getwidth (null);
Intimageheight = Image.getheight (null);
Doubleimageratio = (double) imagewidth/(double) imageheight;
if (Thumbratio < Imageratio) {
thumbheight= (int) (thumbwidth/imageratio);
} else {
thumbwidth= (int) (thumbheight * imageratio);
}
Draworiginal image to thumbnail image object and
Scale ITTO the new size On-the-fly
Bufferedimagethumbimage = new BufferedImage (Thumbwidth, Thumbheight,
BUFFEREDIMAGE.TYPE_INT_RGB);
graphics2dgraphics2d = Thumbimage.creategraphics ();
Graphics2d.setrenderinghint (Renderinghints.key_interpolation,
Renderinghints.value_interpolation_bilinear);
Graphics2d.drawimage (image,0, 0, thumbwidth, thumbheight, NULL);
Savethumbnail image to Outfilename
Bufferedoutputstreamout = new Bufferedoutputstream (
Newfileoutputstream (Outfilename));
Jpegimageencoderencoder = Jpegcodec.createjpegencoder (out);
Jpegencodeparamparam = Encoder.getdefaultjpegencodeparam (thumbimage);
Quality =math.max (0, Math.min (quality, 100));
Param.setquality ((float) quality/100.0f, false);
Encoder.setjpegencodeparam (param);
Encoder.encode (Thumbimage);
Out.close ();
}
Public staticvoid Main (string[] args) throws exception{
Long start =system.currenttimemillis ();
Easythumbnailthumbnail = new Easythumbnail ();
Thumbnail.createthumbnail ("D:/ffm83/fx.jpg", 108, [+], "d:/ffm83/fx_thunmbnail.jpg");
Long end =system.currenttimemillis ();
System.out.println (" Generate thumbnails time:" + (End-start) + "( milliseconds)");
}
}
2 , running results
generate thumbnails Time: 107 ( ms)
A good memory is better than a bad pen. 3-java generating Thumbnails