使用java将图像转换为base64

时间:2015-02-01 22:08:59

标签: java image jsp servlets base64

我需要将图像对象转换为base64对象,以便将其加载到客户端的标记中。

然而,我似乎无法弄清楚如何解决这个问题。是否有人可以轻松使用这段代码?

这是我用来将外部图像链接转换为图像对象的方法

Image image = null;
URL url = new URL(request.getParameter("hdn_path"));
image = ImageIO.read(url);

不确定我是否以正确的方式解决这个问题。

3 个答案:

答案 0 :(得分:10)

使用Apache IOUtilsBase64

byte[] imageBytes = IOUtils.toByteArray(new URL("...")));
String base64 = Base64.getEncoder().encodeToString(imageBytes);

答案 1 :(得分:6)

  • 使用ImageIO.write()编写。
  • ByteArrayOutputStream包装字节数组,以便它可以用作输出流。
  • 使用DatatypeConverter将字节数组转换为base64字符串,从6开始在核心Java中,不需要额外的库

实施例

ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(image, "png", output);
DatatypeConverter.printBase64Binary(output.toByteArray());

答案 2 :(得分:1)

Accepted answer从URL读取文件,如果有人通过从文件系统读取图像来寻找图​​像以Base64编码的方式,则可以使用以下代码段。

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Base64;
import org.apache.commons.io.IOUtils;

public String img2Text(){
    String base64="";
    try{
        InputStream iSteamReader = new FileInputStream("featured-700x467.png");
        byte[] imageBytes = IOUtils.toByteArray(iSteamReader);
        base64 = Base64.getEncoder().encodeToString(imageBytes);
        System.out.println(base64);
    }catch(Exception e){
        e.printStackTrace();
    }
    return "data:image/png;base64,"+base64;
}

返回的base64文本可以在HTML页面中使用,例如下面的示例

<!DOCTYPE html>
<html>
<body>

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACoAAAAqCAYAAADFw8lbAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAfDSURBVFhHrZihb2NHEMatKpUCAgIMQgMOFIZUKg3oH9F/oaCwqo4GFAREVRUdMDWwTgcCopOB6VNlEFXRySDgUUtxKoMAA1+0N7/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