参考资料写了一个生成缩略图的类
程序员文章站
2024-03-14 13:46:52
...
写了有一年多了,还是拿出来,以备后用
package cn.tofishes.util.image;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 生成图片缩略图
* @author ToFishes
*
*/
public class ReduceImage {
/**
* 自定义宽高生成缩略图
* @param imgSrc 原图片的绝对路径名
* @param imgDist 生成缩略图后的存放绝对路径名
* @param widthDist 缩略图的宽度
* @param heightDist 缩略图的高度
*/
public static void reduceImg(String imgSrc, String imgDist, int widthDist,
int heightDist) {
try {
File srcfile = new File(imgSrc);
if (!srcfile.exists()) {
return;
}
Image src = javax.imageio.ImageIO.read(srcfile);
reduceImg(src, imgDist, widthDist, heightDist);
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* 按照图片原有比例生成图片缩略图,maxSize为图片高度、宽度的最大值。
* @param imgSrc 原图片的绝对路径
* @param imgDist 生成缩略图后的存放绝对路径名
* @param maxSize 图片高度、宽度的最大值。
*/
public static void reduceImg(String imgSrc, String imgDist, int maxSize) {
File srcfile = new File(imgSrc);
if (!srcfile.exists()) {
return;
}
try {
Image src = javax.imageio.ImageIO.read(srcfile);
float width = src.getWidth(null);
float height = src.getHeight(null);
/* 获得图片缩放的比例,哪个大就以哪个为标准
* 前面的width或height得设置为float类型,否则相除得整型0
* */
float proportion = width > height ? maxSize/width : maxSize/height;
int widthDist = Math.round(width*proportion);
int heightDist = Math.round(height*proportion);
reduceImg(src, imgDist, widthDist, heightDist);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void reduceImg(Image src, String imgDist, int widthDist,
int heightDist) throws ImageFormatException, IOException {
if (widthDist <= 0 || heightDist <= 0 ) {
throw new ImageFormatException("缩略图高宽不能等于小于0");
}
BufferedImage tag = new BufferedImage(widthDist, heightDist,
BufferedImage.TYPE_INT_RGB);
// tag.getGraphics().drawImage(src.getScaledInstance(widthDist,
// heightDist, Image.SCALE_SMOOTH), 0, 0, null);
tag.getGraphics().drawImage(
src.getScaledInstance(widthDist, heightDist,
Image.SCALE_AREA_AVERAGING), 0, 0, null);
FileOutputStream out = new FileOutputStream(imgDist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
/**
* @param args
*/
public static void main(String[] args) {
String imageSrc = "G:/1218794106_ddvip_459.jpg";
String imgDist = "G:/1218794106.jpg";
long start = System.currentTimeMillis();
ReduceImage.reduceImg(imageSrc, imgDist, 120);
long end = System.currentTimeMillis();
System.out.println("耗用时间为: -- " + (end - start) + "毫秒");
System.out.println("耗用时间为: -- " + (end - start) / 1000.0 + "秒");
}
}