그림 베이스 64 방법

2231 단어 자바
package com.x.common.utils;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class Base64Utils {

  public static void main(String[] args) throws Exception {

    //      
    String url = "C:/Users/Administrator/Desktop/a.jpg";
    //      
    String string = "http://.../a.jpg";

    String str = Base64Utils.ImageToBase64ByLocal(url);

    String ste = Base64Utils.ImageToBase64ByOnline(string);

    System.out.println(str);
  }

  /**
   *        base64   
   * @param imgFile	      
   * @return
   *
   * @author ZHANGJL
   * @dateTime 2018-02-23 14:40:46
   */
  public static String ImageToBase64ByLocal(String imgFile) {//                ,     Base64    

    InputStream in = null;
    byte[] data = null;

    //         
    try {
      in = new FileInputStream(imgFile);

      data = new byte[in.available()];
      in.read(data);
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    //      Base64  
    BASE64Encoder encoder = new BASE64Encoder();
    //   Base64           
    return encoder.encode(data);
  }



  /**
   *        base64   
   *
   * @param imgURL	      
   * @return
   *
   * @author ZHANGJL
   * @dateTime 2018-02-23 14:43:18
   */
  public static String ImageToBase64ByOnline(String imgURL) {
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    try {
      //   URL
      URL url = new URL(imgURL);
      byte[] by = new byte[1024];
      //     
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setConnectTimeout(5000);
      InputStream is = conn.getInputStream();
      //         
      int len = -1;
      while ((len = is.read(by)) != -1) {
        data.write(by, 0, len);
      }
      //    
      is.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    //      Base64  
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data.toByteArray());
  }

}

좋은 웹페이지 즐겨찾기