package com.bancool.common;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import sun.awt.image.codec.JPEGImageEncoderImpl;
/**
* 图片工具类
* @author xin
*
*/
public class ImageTool {
/**
* 图片等比例缩放
* @param src 地址
* @param maxWidth 最大宽度
* @param maxHeight 最大高度
* @return
*/
public static boolean change(String src,int maxWidth,int maxHeight){
int width,height;
double scale;//比例
try {
File file = new File(src);
Image image = ImageIO.read(file);
//等比例运算
width=image.getWidth(null);
height=image.getHeight(null);
scale=(width+0.1)/(height+0.1);
if(scale>=(maxWidth+0.1)/(maxHeight+0.1)&&width>maxWidth){
width=maxWidth;
height=(int)(maxWidth/scale);
}
if(scale<(maxWidth+0.1)/(maxHeight+0.1)&&height>maxHeight){
height=maxHeight;
width=(int)(maxHeight*scale);
}
//创建图像
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
bi.getGraphics().drawImage(image,0,0,width, height, null);
//转码输出
FileOutputStream out = new FileOutputStream(file);
JPEGImageEncoderImpl encoder = new JPEGImageEncoderImpl(out);
encoder.encode(bi);
out.close();
} catch (IOException e) {
}
return true;
}
}
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import sun.awt.image.codec.JPEGImageEncoderImpl;
/**
* 图片工具类
* @author xin
*
*/
public class ImageTool {
/**
* 图片等比例缩放
* @param src 地址
* @param maxWidth 最大宽度
* @param maxHeight 最大高度
* @return
*/
public static boolean change(String src,int maxWidth,int maxHeight){
int width,height;
double scale;//比例
try {
File file = new File(src);
Image image = ImageIO.read(file);
//等比例运算
width=image.getWidth(null);
height=image.getHeight(null);
scale=(width+0.1)/(height+0.1);
if(scale>=(maxWidth+0.1)/(maxHeight+0.1)&&width>maxWidth){
width=maxWidth;
height=(int)(maxWidth/scale);
}
if(scale<(maxWidth+0.1)/(maxHeight+0.1)&&height>maxHeight){
height=maxHeight;
width=(int)(maxHeight*scale);
}
//创建图像
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
bi.getGraphics().drawImage(image,0,0,width, height, null);
//转码输出
FileOutputStream out = new FileOutputStream(file);
JPEGImageEncoderImpl encoder = new JPEGImageEncoderImpl(out);
encoder.encode(bi);
out.close();
} catch (IOException e) {
}
return true;
}
}