Java 將圖片轉(zhuǎn)換成base64編碼字符串

大家可能會注意到,網(wǎng)頁中類似:

<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABA......" />

那么這是什么呢?這是Data URI scheme。
Data URI scheme是在RFC2397中定義的,目的是將一些小的數(shù)據(jù),直接嵌入到網(wǎng)頁中,從而不用再從外部文件載入。比如上面那串字符,其實是一張小圖片,將這些字符復(fù)制黏貼到火狐的地址欄中并轉(zhuǎn)到,就能看到它了。
在上面的Data URI中,data表示取得數(shù)據(jù)的協(xié)定名稱,image/png 是數(shù)據(jù)類型名稱,base64 是數(shù)據(jù)的編碼方法,逗號后面就是這個image/png文件base64編碼后的數(shù)據(jù)。

java將圖片轉(zhuǎn)換成base64編碼字符串其實很簡單。

/**
 * 將圖片轉(zhuǎn)換成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;
}

這樣做的好處是,節(jié)省了一個HTTP 請求。壞處是瀏覽器不會緩存這種圖像。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容