使用Thumbnails压缩或放大图片大小(java)

时间:2025-03-20 10:09:07
package com.web.framework.bbpp.module.yituhezisone.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.coobird.thumbnailator.Thumbnails; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class CompressImage { public static void main(String[] args) { String str = "base64编码格式的图片"; CompressImage com = new CompressImage(); //因为我使用的是base64编码格式的图片数据,所以需要先将base转为字节数组 byte[] decode = com.decode(str); //将字节数组数据传入压缩方法中compressByteImage str = com.compressByteImage(decode); System.out.println("压缩后的图片数据"+str); } /** * byte数组 转换为 Base64字符串 */ public String encode(byte[] data) { return new BASE64Encoder().encode(data); } /** * Base64字符串 转换为 byte数组 */ public byte[] decode(String base64) { try { return new BASE64Decoder().decodeBuffer(base64); } catch (IOException e) { e.printStackTrace(); } return new byte[0]; } public String compressByteImage(byte[] bytes) throws IOException { //先将字节数组数据转为ByteArrayInputStream 形式 ByteArrayInputStream ins = new ByteArrayInputStream(bytes); ByteArrayOutputStream out = new ByteArrayOutputStream(); //进行压缩 out就是压缩后的数据 Thumbnails.of(ins).scale(0.99f).toOutputStream(out); //将ByteArrayOutputStream形式转为字节数组 byte[] data = out.toByteArray(); //将字节数组数据转为base64的格式 String imageStr = encode(data); return imageStr; }