package com.xcong.excoin.utils; import cn.hutool.core.util.StrUtil; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; public class ImageUtils { public static boolean base64ToImg(String base64Str, String imgPath) { // 图像数据为空 if (StrUtil.isBlank(base64Str)) { return false; } BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解码 byte[] bytes = decoder.decodeBuffer(base64Str); for (int i = 0; i < bytes.length; ++i) { // 调整异常数据 if (bytes[i] < 0) { bytes[i] += 256; } } // 生成jpeg图片 OutputStream out = new FileOutputStream(imgPath); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } public static String imgToBase64(String imgPath) { byte[] data = null; // 读取图片字节数组 try { InputStream in = new FileInputStream(imgPath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64编码过的字节数组字符串 return encoder.encode(data); } public static void main(String[] args) { base64ToImg(imgToBase64("/Users/helius/Pictures/123.jpg"), "/Users/helius/Desktop/123.jpg"); } }