czt
2026-01-10 e2abf0dd0c49bc6e82f428ec747865cc806147a3
fzzy-igdss-core/src/main/java/com/fzzy/igds/utils/Base64Util.java
@@ -1,15 +1,18 @@
package com.fzzy.igds.utils;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.util.Base64;
/**
 * @Description 图片Base处理
 * @Author CZT
 * @Date 2026/1/7 11:07
 */
@Slf4j
public class Base64Util {
   public static String BASE_IMG_START = "data:image/jpg;base64,";
@@ -85,4 +88,59 @@
      }
   }
   /**
    * base64转为图片
    *
    * @param path   文件路径:到文件夹即可,代码里会在文件夹里生成对应的jpg文件
    * @param base64
    * @return
    */
   public static String base64ToJpg(String path, String fileName, String base64) {
      // 判断文件路径是否存在
      File filePath = new File(path);
      if (!filePath.exists()) {
         filePath.mkdirs();
      }
      // 创建文件
      String jpgFile = path + "\\" + fileName + ".jpg";
      File file = new File(jpgFile);
      boolean jpgFileExist = false;
      try {
         jpgFileExist = file.createNewFile();
         log.info("jpg文件创建成功");
      } catch (IOException e) {
         log.info("jpg文件创建失败");
         e.printStackTrace();
      }
      if (jpgFileExist) {
         // 解密
         Base64.Decoder decoder = Base64.getDecoder();
         // 去掉base64前缀 data:image/jpeg;base64,
         base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length());
         byte[] b = decoder.decode(base64);
         // 处理数据
         for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
               b[i] += 256;
            }
         }
         // 保存图片
         try {
            FileOutputStream out = new FileOutputStream(jpgFile);
            out.write(b);
            out.flush();
            out.close();
            // 写入成功返回文件路径
            return jpgFile;
         } catch (FileNotFoundException e) {
            log.info("文件未找到");
            e.printStackTrace();
         } catch (IOException e) {
            log.info("写入失败");
            e.printStackTrace();
         }
      }
      return "文件不存在";
   }
}