package com.cj.photography.util; import sun.misc.BASE64Decoder; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.UUID; /** * @author Jamin <br> * @date 2019/4/10 10:33 <br> * 将base64转为图片的工具 */ public class Base64 { static String base64 = "base64,"; public static String generateImage(String imgStr, String fileName, String type) { if (imgStr == null) { // 图像数据为空 return null; } BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } // 生成jpeg图片 String imgFilePath = "D:\\upload\\images\\" + fileName + "." + type; File file = new File(imgFilePath); if (!file.getParentFile().exists()) { boolean result = file.getParentFile().mkdirs(); if (!result) { return null; } } OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); // 修改图片地址 String imgAdress = "/img/" + fileName + "." + type; return imgAdress; } catch (Exception e) { return null; } } /** * 从富文本编辑器中的内容 */ public static String conversionImage(String str) { // while 循环是否含有base64 // 有把字符串截取出来 // 要返回的字符串 String strreturn = str; while (str.contains(base64)) { // 复制一个str用于存储截取的base64 String str1 = str; // 截取image str1 = str1.substring(str1.indexOf("image")); // 用于二次截取的变量 String str3 = str1; String type = str1.substring(str1.indexOf("image/") + 6, str1.indexOf(";base64")); // 开始点 int i = str1.indexOf(base64) + base64.length(); // 结束点 int i1 = str1.indexOf("=\"") + 1; // str1截取获取到base64 str1 = str1.substring(i, i1); // 执行字符串转图片操做 String imgurl = generateImage(str1, UUID.randomUUID().toString(), type); // 转换为图片后将字符串替换 if (imgurl != null) { str1 = str; int i2 = str1.indexOf("data:"); str1 = str1.substring(i2); int i3 = str1.indexOf("=\"") + 1; String src = str1.substring(0, i3); strreturn = strreturn.replace(src, imgurl); } // str从结束点截取 str = str.substring(i1); } return strreturn; } /** * 裁剪头像 普通图片base64 * * @param str iconBase64码 * @return image 地址 */ public static String base64Image(String str) { String str1 = str; String type = str.substring(str.indexOf("image/") + 6, str.indexOf(";base64")); int i = str1.indexOf(base64) + base64.length(); String substring = str1.substring(i); String s = generateImage(substring, UUID.randomUUID().toString(), type); return s; } }