今天在工作中遇到了个问题:用户上传的人脸图片像素过大,硬件机无法识别,所以要对文件进行裁剪
public class ImageCropUtils {
/**
* @param fromFileStr 要裁剪的图片路径
* @param saveToFileStr 保存的图片地址
* @param suffix 图片后缀
* @param width 裁剪后宽度
* @param height 裁剪后高度
*
* @return 成功或失败
* */
public static boolean createThumbnail( String fromFileStr, String saveToFileStr, String suffix, int width, int height ) throws Exception {
// fileExtNmae是图片的格式 gif JPG 或png
// String fileExtNmae="";
File F = new File(fromFileStr);
if (!F.isFile()){
return false;
}
File ThF = new File(saveToFileStr);
BufferedImage buffer = ImageIO.read(F);
/*
* 核心算法,计算图片的压缩比
*/
int w= buffer.getWidth();
int h=buffer.getHeight();
double ratiox = 1.0d;
double ratioy = 1.0d;
ratiox= w * ratiox / width;
ratioy= h * ratioy / height;
if( ratiox >= 1){
if(ratioy < 1){
ratiox = height * 1.0 / h;
}else{
if(ratiox > ratioy){
ratiox = height * 1.0 / h;
}else{
ratiox = width * 1.0 / w;
}
}
}else{
if(ratioy < 1){
if(ratiox > ratioy){
ratiox = height * 1.0 / h;
}else{
ratiox = width * 1.0 / w;
}
}else{
ratiox = width * 1.0 / w;
}
}
/*
* 对于图片的放大或缩小倍数计算完成,ratiox大于1,则表示放大,否则表示缩小
*/
AffineTransformOp op = new AffineTransformOp(AffineTransform
.getScaleInstance(ratiox, ratiox), null);
buffer = op.filter(buffer, null);
//从放大的图像中心截图
buffer = buffer.getSubimage((buffer.getWidth()-width)/2, (buffer.getHeight() - height) / 2, width, height);
//写入文件
ImageIO.write(buffer, suffix, ThF);
return true;
}
/**
* @param fromFileInputStream 要裁剪的图片
* @param saveToFileStr 保存的图片地址
* @param suffix 图片后缀
* @param width 裁剪后宽度
* @param height 裁剪后高度
*
* @return 成功或失败
* */
public static boolean createThumbnail(InputStream fromFileInputStream, String saveToFileStr, String suffix, int width, int height ) throws Exception{
// fileExtNmae是图片的格式 gif JPG 或png
// String fileExtNmae="";
File ThF = new File(saveToFileStr);
BufferedImage buffer = ImageIO.read(fromFileInputStream);
/*
* 核心算法,计算图片的压缩比
*/
int w= buffer.getWidth();
int h=buffer.getHeight();
double ratiox = 1.0d;
double ratioy = 1.0d;
ratiox= w * ratiox / width;
ratioy= h * ratioy / height;
if( ratiox >= 1){
if(ratioy < 1){
ratiox = height * 1.0 / h;
}else{
if(ratiox > ratioy){
ratiox = height * 1.0 / h;
}else{
ratiox = width * 1.0 / w;
}
}
}else{
if(ratioy < 1){
if(ratiox > ratioy){
ratiox = height * 1.0 / h;
}else{
ratiox = width * 1.0 / w;
}
}else{
ratiox = width * 1.0 / w;
}
}
/*
* 对于图片的放大或缩小倍数计算完成,ratiox大于1,则表示放大,否则表示缩小
*/
AffineTransformOp op = new AffineTransformOp(AffineTransform
.getScaleInstance(ratiox, ratiox), null);
buffer = op.filter(buffer, null);
//从放大的图像中心截图
buffer = buffer.getSubimage((buffer.getWidth()-width)/2, (buffer.getHeight() - height) / 2, width, height);
try {
ImageIO.write(buffer, suffix, ThF);
} catch (Exception ex) {
ex.printStackTrace();
}
return true;
}
public static void main(String[] args) {
try {
ImageCropUtils.createThumbnail("G:\\face\\韦钰莹.JPG", "G:\\face\\韦钰莹3.JPG","png",280,280);
} catch (Exception e) {
e.printStackTrace();
}
}
}