大家可能會注意到,網頁中類似:
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABA......" />
那么這是什么呢?這是Data URI scheme。
Data URI scheme是在RFC2397中定義的,目的是將一些小的數據,直接嵌入到網頁中,從而不用再從外部文件載入。比如上面那串字符,其實是一張小圖片,將這些字符復制黏貼到火狐的地址欄中并轉到,就能看到它了。
在上面的Data URI中,data表示取得數據的協定名稱,image/png 是數據類型名稱,base64 是數據的編碼方法,逗號后面就是這個image/png文件base64編碼后的數據。
java將圖片轉換成base64編碼字符串其實很簡單。
/**
* 將圖片轉換成base64格式進行存儲
* @param imagePath
* @return
*/
public static String encodeToString(String imagePath) throws IOException {
String type = StringUtils.substring(imagePath, imagePath.lastIndexOf(".") + 1);
BufferedImage image = ImageIO.read(new File(imagePath));
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
這樣做的好處是,節省了一個HTTP 請求。壞處是瀏覽器不會緩存這種圖像。