import org.apache.commons.lang3.StringUtils; import org.apache.tomcat.util.codec.binary.Base64; import java.io.*; public class Base64Util { private static final LoggerUtil logger = LogFactory.getLogger(Base64Util.class); //圖片轉化成base64字符串 public static String GetImageStr(String imgFile) { //將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理 byte[] data = null; //讀取圖片字節數組 try (InputStream in = new FileInputStream(imgFile);) { data = new byte[in.available()]; in.read(data); } catch (IOException e) { logger.info("Base64Util GetImageStr e:" + e.getLocalizedMessage()); } //返回Base64編碼過的字節數組字符串 return Base64.encodeBase64String(data); } //base64字符串轉化成圖片 public static String GenerateImage(String imgStr, String fileName) { //對字節數組字符串進行Base64解碼並生成圖片 String imgUrl = ""; //圖像數據爲空 if (StringUtils.isBlank(imgStr)) return imgUrl; //Base64解碼 byte[] b = Base64.decodeBase64(imgStr); for (int i = 0; i < b.length; ++i) { //調整異常數據 if (b[i] < 0) { b[i] += 256; } } //文件目錄不存在則建立 File outFile = new File(CommonConstant.FILEPATH); if (!outFile.exists()) { outFile.mkdirs(); } //文件最終的存儲位置 File dest = new File(CommonConstant.FILEPATH + fileName); //判斷目標文件所在的目錄是否存在 if (!dest.getParentFile().exists()) { //建立目錄 if (!dest.getParentFile().mkdirs()) { return imgUrl; } } //新生成的圖片 imgUrl = CommonConstant.FILEPATH + fileName; //這種寫法不須要flush或者close 會自動關閉 FileOutputStream 實現了java中的java.lang.AutoCloseable接口。 try (OutputStream out = new FileOutputStream(CommonConstant.FILEPATH + fileName);) { out.write(b); } catch (Exception e) { logger.info("Base64Util GenerateImage e:" + e.getLocalizedMessage()); } finally { return imgUrl; } } }