|
|
@@ -0,0 +1,71 @@
|
|
|
+package me.zhengjie.base.util;
|
|
|
+
|
|
|
+
|
|
|
+import cn.hutool.core.io.IoUtil;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import net.coobird.thumbnailator.Thumbnails;
|
|
|
+import org.apache.commons.codec.binary.Base64;
|
|
|
+import sun.misc.BASE64Decoder;
|
|
|
+
|
|
|
+import javax.imageio.ImageIO;
|
|
|
+import java.awt.image.BufferedImage;
|
|
|
+import java.io.ByteArrayInputStream;
|
|
|
+import java.io.ByteArrayOutputStream;
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.InputStream;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 图片压缩工具类
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+public class ImageUtil {
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 压缩base64编码至200k以内
|
|
|
+ *
|
|
|
+ * @param base64Img
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public static String resizeImage(String base64Img) {
|
|
|
+ try {
|
|
|
+ BASE64Decoder decoder = new BASE64Decoder();
|
|
|
+ byte[] bytes1 = decoder.decodeBuffer(base64Img);
|
|
|
+ InputStream stream = new ByteArrayInputStream(bytes1);
|
|
|
+ BufferedImage src = ImageIO.read(stream);
|
|
|
+ //BufferedImage output = Thumbnails.of(src).size(src.getWidth() / 3, src.getHeight() / 3).asBufferedImage();
|
|
|
+ BufferedImage output = Thumbnails.of(src).size(300 , 300).asBufferedImage();
|
|
|
+ String base64 = imageToBase64(output);
|
|
|
+ if (base64.length() - base64.length() / 8 * 2 > 200000) {
|
|
|
+ output = Thumbnails.of(output).scale(1 / (base64.length() / 200000)).asBufferedImage();
|
|
|
+ base64 = imageToBase64(output);
|
|
|
+ }
|
|
|
+ return base64;
|
|
|
+ } catch (Exception e) {
|
|
|
+ return base64Img;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * BufferedImage转换成base64,在这里需要设置图片格式,因为我需要jpg格式就设置了jpg
|
|
|
+ */
|
|
|
+ public static String imageToBase64(BufferedImage bufferedImage) {
|
|
|
+ Base64 encoder = new Base64();
|
|
|
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
|
|
+ try {
|
|
|
+ ImageIO.write(bufferedImage, "png", baos);
|
|
|
+ } catch (IOException e) {
|
|
|
+ }
|
|
|
+ return new String(encoder.encode((baos.toByteArray())));
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取base64的kb大小
|
|
|
+ * @param base64
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public static Integer imageSize(String base64){
|
|
|
+ Integer strLength = base64.length();
|
|
|
+ return (strLength-(strLength/8)*2)/1024;
|
|
|
+ }
|
|
|
+}
|