Java implements converting image to base64 string java implements converting base64 string to image, javabase64
Java image to base64 string, base64 string to image, the specific content is as follows
1. Convert the image to a base64 string:
/*** Convert a base64 encoded String to an 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 ;}// if the folder does not exist, 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 ;}}
2. convert a base64 string to an image:
/*** Convert an image to a 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 ();} // encrypted 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); }
:
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.