1. 程式人生 > >Java實現圖片與base64位編碼互相轉換

Java實現圖片與base64位編碼互相轉換

Base64目前主要用於HTML5、移動開發等不考慮IE6的場景中。
Base64格式
data:[][;charset=][;base64],
Base64 在CSS中的使用
.demoImg{ background-image: url("data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL...."); }
Base64 在HTML中的使用
<img width="40" height="30" src="data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL...." />
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; import java.io.*;public class Base64Img { public static void main(String[] args) { // 測試從圖片檔案轉換為Base64編碼 String img64Str = getImg64("D:\\tmp\\QQ圖片20160401133853.jpg"); System.out.println(img64Str); // 測試從Base64編碼轉換為圖片檔案 // String strImg = "這裡放64位編碼"; System.out.println(Img64SaveToImgFile
(img64Str, "D:\\tmp\\4afbfbedab64034fe3c2af48adc379310a551d74.jpg"));} /** * 圖片轉換為 img64字串 * @param imgPath * @return */ public static String getImg64(String imgPath) { byte[] data = null; // 讀取圖片位元組陣列 try { InputStream in = new FileInputStream(imgPath); data = new byte[in.available()];
in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 對位元組陣列Base64編碼 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);// 返回Base64編碼過的位元組陣列字串 } /** * img64字串 轉換為圖片 * @param img64Str * @param imgPath * @return */ public static boolean Img64SaveToImgFile(String img64Str, String imgPath) { if (img64Str == null) // 影象資料為空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解碼 byte[] bytes = decoder.decodeBuffer(img64Str); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 調整異常資料 bytes[i] += 256; } } // 生成jpeg圖片 OutputStream out = new FileOutputStream(imgPath); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } }