Maven中用到的依赖:
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
base64转换成BufferedImage:
public static BufferedImage base64String2BufferedImage(String base64string) {
BufferedImage image = null;
try {
InputStream stream = BaseToInputStream(base64string);
image = ImageIO.read(stream);
} catch (IOException e) {
LOG.info("");
}
return image;
}
BufferedImage转换成base64,在这里需要设置图片格式,如下是jpg格式图片:
public static String imageToBase64(BufferedImage bufferedImage) {
Base64 encoder = new Base64();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, "jpg", baos);
} catch (IOException e) {
LOG.info("");
}
return new String(encoder.encode((baos.toByteArray())));
}
Base64转换成InputStream:
private static InputStream BaseToInputStream(String base64string){
ByteArrayInputStream stream = null;
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes1 = decoder.decodeBuffer(base64string);
stream = new ByteArrayInputStream(bytes1);
} catch (Exception e) {
// TODO: handle exception
}
return stream;
}
压缩图片至40k之内,将原图片的长宽分别压缩为原图片的1/3,如果图片大小大于40k,则继续进行压缩。
public static String resizeImageTo40K(String base64Img) {
try {
BufferedImage src = base64String2BufferedImage(base64Img);
BufferedImage output = Thumbnails.of(src).size(src.getWidth()/3, src.getHeight()/3).asBufferedImage();
String base64 = imageToBase64(output);
if (base64.length() - base64.length() / 8 * 2 > 40000) {
output = Thumbnails.of(output).scale(1/(base64.length()/40000)).asBufferedImage();
base64 = imageToBase64(output);
}
return base64;
} catch (Exception e) {
return base64Img;
}
}
图片的Base64大小计算为:
base64.length() - base64.length() / 8 * 2
图片压缩的验证方法:
public static void main(String[] args){
String base64="iVBORw0KGgoAAAANSUhEUgAAAMIAAACdCAYAAADmOacTAACAAElEQVR42ux9h3+UZda2f8q+ryRTUwm9qAgINkTEggV7XXsvq65r17XXtffeuwghbTLpPZOZSSOEAO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