Java picture to base64 string, base64 string to picture, the specific content is as follows
1. Image to base64 string:
/** * base64-encoded string to image* @param imgStr base64-encoded string* @param path Image path* @return */ public static boolean base64StrToImage(String imgStr, String path) { if (imgStr == null) return false; BASE64Decoder decoder = new BASE64Decoder(); try { // Decrypt byte[] b = decoder.decodeBuffer(imgStr); // Process data for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } //File is automatically created if the folder does not exist. 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; } }2. base64 string to picture:
/** * Image to base64 string* @param imgFile Image path* @return */ public static String imageToBase64Str(String imgFile) { InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream(imgFile); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } // Encryption BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); }3. Test:
public static void main(String[] args) { String base64Str = imageToBase64Str("D:/pic/001.jpg"); System.out.println(base64Str); boolean b = base64StrToImage(base64Str, "D:/pic/temp/002.jpg"); System.out.println(b); }Reproduction image:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.