电子商务网站等系统,有大量的图片;从加载速度和流量等角度出发,会使用比较多的缩略图。
1、创建图片的缩略图源代码
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;
/**
* 生成缩略图
* @author 范芳铭
*/
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, 100, 100, "d:/ffm83/fx_thunmbnail.jpg");
long end =System.currentTimeMillis();
System.out.println("生成缩略图耗时:" + (end - start) + "(毫秒)");
}
}
2、运行结果
生成缩略图耗时:107(毫秒)
原文地址:http://blog.csdn.net/ffm83/article/details/43233331