package com.jiwu.utils;
import java.awt.*;
import java.io.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.io.*;
/**
* @author jxialiang
* @date 2007-09-27
*/
public class ImgUtil {
private static final Log logger = LogFactory.getLog(ImgUtil.class);
public ImgUtil() {
}
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);
int width = src.getWidth(null);
int height = src.getHeight(null);
if (width <= widthdist && height <= heightdist) {
//SysUtil.cpoyFile(imgsrc, imgdist);
FileUtils.copyFile(new File(imgsrc), new File(imgdist));
return;
}
//宽度除以高度的比例
float wh = (float) width / (float) height;
if (wh > 1) {
float tmp_heigth = (float) widthdist / wh;
BufferedImage tag = new BufferedImage(widthdist, (int) tmp_heigth,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src, 0, 0, widthdist, (int) tmp_heigth, null);
FileOutputStream out = new FileOutputStream(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
else {
if (width <= widthdist && wh > 0.1f) {
FileUtils.copyFile(new File(imgsrc), new File(imgdist));
return;
}
if (width > widthdist && wh > 0.1f) {
float tmp_heigth = (float) widthdist / wh;
BufferedImage tag = new BufferedImage(widthdist, (int) tmp_heigth,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src, 0, 0, widthdist, (int) tmp_heigth, null);
FileOutputStream out = new FileOutputStream(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
return;
}
float tmp_width = (float) heightdist * wh;
BufferedImage tag = new BufferedImage( (int) tmp_width, heightdist,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src, 0, 0, (int) tmp_width, heightdist, null);
FileOutputStream out = new FileOutputStream(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
}
catch (IOException ex) {
logger.error(ex);
}
}
//生成原始图片到特定磁盘位置
public static void createOrgImage(File srcFile,File dstFile){
try {
FileUtils.copyFile(srcFile, dstFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return dstPath;
}
//生成缩略图
//其中saveImagePath 为原始图片的全路径,saveThumbBasePath保存缩略图基路径,fileName文件名,width,height生成缩略图宽,高
//public static void createThumb(String saveOrgImagePath,String saveThumbBasePath,String location,String fileName,int width,int height){
public static void createThumb(String srcImagePath,String distImagePath,int width,int height){
String imgdist = distImagePath;
String imgsrc = srcImagePath;
reduceImg(imgsrc, imgdist, width, height);
}
public static void main(String [] args){
ImgUtil i = new ImgUtil();
i.reduceImg("D:/2679321.jpg", "D:/usernoface.gif", 48, 48);
}
}