Java implements converting image to base64 string java implements converting base64 string to image, javabase64

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.