我在项目中遇到了对接人脸识别的需求,上游需要对上传的图片进行压缩,并且严格限制图片的大小和长宽。
我们APP端也会对图片进行处理,自己也找了一些对图片进行处理的方法,这里记录一下,方便学习使用。
注:下面的代码只是我自己测试使用,具体业务还需要进行处理。
代码中使用到的这个类【import com.sun.image.codec.jpeg.JPEGCodec;】在JDK1.7以后就删除了,可以使用这个【ImageIO.write】进行代替
转自:https://blog.csdn.net/qq844579582/article/details/52790344
package com.payment.biz.util;
import com.payment.biz.factory.log.LogEx;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
/**
* @Author: **
* @Company: ***
* @Date: 2018-12-06 18:29
* @Description: 图片压缩工具类
*/
public class CommonPictureUtils {
private CommonPictureUtils() {
}
/**
* @Author: **
* @Company: ***
* @Description: 是否等比压缩图片的方法,是的话proportion=true,只需设置一个新图片的宽度,否的话proportion=false,新图片的宽高都需要设置
* @Date: 2018/12/7 10:32
* @Param: [filePath, outputWidth, outputHeight, proportion]
* @Return: java.lang.String
*/
public static String compressPic(String filePath, int outputWidth, int outputHeight, boolean proportion) throws Exception {
//获得文件源
File file = new File(filePath);
if (!file.exists()) {
return "";
}
//imageIO.read(arg);图片解析,可传入文件,文件输入流等
Image img = ImageIO.read(file);
if (img.getWidth(null) == -1) {
return "";
} else {
int newWidth;
int newHeight;
//判断是否等比缩放
if (proportion) {
double rate = (double) img.getWidth(null) / (double) outputWidth;
newWidth = outputWidth;
newHeight = (int) ((double) img.getHeight(null) / rate);
} else {
newWidth = outputWidth;
newHeight = outputHeight;
}
/*
* Image.SCALE_SMOOTH的缩略算法生成缩略图片的平滑度的优先级比速度高,生成的图片质量好但是速度慢
* 根据具体要求取舍时间或是质量
*/
FileOutputStream out = null;
try {
BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
/* @param img the specified image to be drawn.
* @param x x坐标.
* @param y y坐标.
* @param width the width of the rectangle.
* @param height the height of the rectangle.
* @param observer 像素是否被改变
*/
tag.getGraphics().drawImage(img, 0, 0, newWidth, newHeight, null);
out = new FileOutputStream(filePath);
//JPEGImageEncoder可适用于其他图片的类型的转换:
// 注意下面这个注释掉的类在JDK1.7以后就删除不再使用了,可以使用ImageIO.write进行代替
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// encoder.encode(tag);
ImageIO.write(tag, "jpg", out);
out.flush();
out.close();
tag.flush();
tag = null;
} catch (Exception e) {
e.printStackTrace();
LogEx.BI("9005", "CommonPictureUtils", filePath, "压缩图片异常:[{}].[{}]", new Object[]{filePath, e.getMessage()});
return "";
} finally {
if (out != null) {
out.close();
}
}
return filePath;
}
}
public static void main(String[] args) throws Exception {
String s = CommonPictureUtils.compressPic("F:\\temp\\123 - 副本.jpg", 400, 400, true);
System.out.println(s);
}
}