Java代碼圖片字符串互轉
/** * 將base64字符串轉成圖片 * TODO * @param imgStr base64圖片字符串 * @param path 目標輸出路徑 * @return */ public static boolean base64StrToImage(String imgStr, String path) { if (imgStr == null) return false; BASE64Decoder decoder = new BASE64Decoder(); try { // 解密base64圖片字符串 byte[] b = decoder.decodeBuffer(imgStr); // 處理數據,把負的byte字節數據改為正的,作用未知 for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } File tempFile = new File(path); //文件夾不存在則自動創建 if (!tempFile.getParentFile().exists()) { tempFile.getParentFile().mkdirs(); } OutputStream out = new FileOutputStream(tempFile); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } /* 圖片轉base64字符串 * @param imgFile 圖片路徑 * @return base64字符串格式的圖片 */ public static String imageToBase64Str(String imgFile) { InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream(imgFile); data = new byte[inputStream.available()]; //根據文件流字節大小初始化data字節數組大小 inputStream.read(data); //將流讀入data inputStream.close(); //關閉流 } catch (IOException e) { e.printStackTrace(); } //將圖片數組加密 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); } public static void main(String[] args) { String base64Str = imageToBase64Str("D:/20190307/2.jpg"); System.out.println(base64Str); boolean b = base64StrToImage(base64Str, "D:/3.jpg"); System.out.println(b); }