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; } }