Convert a picture to a Base64 string Java code

Source: Internet
Author: User
Tags base64

/**

    • @Descriptionmap Convert a picture file to a byte array string and encode it Base64
    • @author Temdy
    • @Date 2015-01-26
    • Path to @param path picture
    • @return
      */
      public static string ImageToBase64 (string path) {//Converts the picture file to a byte array string and encodes it Base64
      byte[] data = null;
      Reading a picture byte array
      try {
      InputStream in = new FileInputStream(path);data = new byte[in.available()];in.read(data);in.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      BASE64 encoding of byte arrays
      Base64encoder encoder = new Base64encoder ();
      return Encoder.encode (data);//returns BASE64 encoded byte array string
      }

/**

    • @Descriptionmap Base64 decoding a byte array string and generating a picture
    • @author Temdy
    • @Date 2015-01-26
    • @param base64 Pictures Base64 Data
    • Path to @param path picture
    • @return
      */
      public static Boolean Base64toimage (String base64, String path) {////byte array string Base64 decoded and generated picture
      if (base64 = = null) {//image data is empty
      return false;
      }
      Base64decoder decoder = new Base64decoder ();
      try {
      // Base64解码byte[] bytes = decoder.decodeBuffer(base64);for (int i = 0; i < bytes.length; ++i) {    if (bytes[i] < 0) {// 调整异常数据        bytes[i] += 256;    }}// 生成jpeg图片OutputStream out = new FileOutputStream(path);out.write(bytes);out.flush();out.close();return true;
      } catch (Exception e) {
      return false;
      }
      }

Convert a picture to a Base64 string Java code

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.