1. 程式人生 > 程式設計 >Java基於Base64實現編碼解碼圖片檔案

Java基於Base64實現編碼解碼圖片檔案

BASE64 編碼是一種常用的字元編碼,在很多地方都會用到。但base64不是安全領域下的加密解密演算法。能起到安全作用的效果很差,而且很容易破解,他核心作用應該是傳輸資料的正確性,有些閘道器或系統只能使用ASCII字元。Base64就是用來將非ASCII字元的資料轉換成ASCII字元的一種方法,而且base64特別適合在http,mime協議下快速傳輸資料。

1、編碼與解碼程式碼如下所示:

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
 
import javax.imageio.ImageIO;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
/**
 * @author zxn
 * @version 建立時間:2014-7-2 上午11:40:40
 * 
 */
public class ImageUtils {
  /**
   * 將網路圖片進行Base64位編碼
   * 
   * @param imgUrl
   *      圖片的url路徑,如http://.....xx.jpg
   * @return
   */
  public static String encodeImgageToBase64(URL imageUrl) {// 將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理
    ByteArrayOutputStream outputStream = null;
    try {
      BufferedImage bufferedImage = ImageIO.read(imageUrl);
      outputStream = new ByteArrayOutputStream();
      ImageIO.write(bufferedImage,"jpg",outputStream);
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 對位元組陣列Base64編碼
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(outputStream.toByteArray());// 返回Base64編碼過的位元組陣列字串
  }
 
  /**
   * 將本地圖片進行Base64位編碼
   * 
   * @param imgUrl
   *      圖片的url路徑,如http://.....xx.jpg
   * @return
   */
  public static String encodeImgageToBase64(File imageFile) {// 將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理
    ByteArrayOutputStream outputStream = null;
    try {
      BufferedImage bufferedImage = ImageIO.read(imageFile);
      outputStream = new ByteArrayOutputStream();
      ImageIO.write(bufferedImage,outputStream);
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 對位元組陣列Base64編碼
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(outputStream.toByteArray());// 返回Base64編碼過的位元組陣列字串
  }
 
  /**
   * 將Base64位編碼的圖片進行解碼,並儲存到指定目錄
   * 
   * @param base64
   *      base64編碼的圖片資訊
   * @return
   */
  public static void decodeBase64ToImage(String base64,String path,String imgName) {
    BASE64Decoder decoder = new BASE64Decoder();
    try {
      FileOutputStream write = new FileOutputStream(new File(path
          + imgName));
      byte[] decoderBytes = decoder.decodeBuffer(base64);
      write.write(decoderBytes);
      write.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

2、直接在頁面上顯示base64編碼的圖片

 <html>
 <body>
 <img src='data:image/jpg;base64,base64碼'/> 
 </body>
 </html>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。