技术杂谈

Java 将图片转换成base64编码字符串

2015-12-17  本文已影响2899人  Devid

大家可能会注意到,网页中类似:

<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 请求。坏处是浏览器不会缓存这种图像。

上一篇下一篇

猜你喜欢

热点阅读