JSP 用java将图像转换为base64

s5a0g9ez  于 2022-12-07  发布在  Java
关注(0)|答案(3)|浏览(318)

我需要将一个图像对象转换为base64对象,以便将其加载到客户端的标记中。
然而,我似乎不知道如何拉这一关。有没有人谁有一个代码,这我可以很容易地使用?
这就是我用来将外部图像链接转换为图像对象的代码

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

我不确定我这样做是否正确。

r3i60tvu

r3i60tvu1#

使用Apache IOUtilsBase64

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

bqf10yzr2#

  • 使用ImageIO.write()进行写入。
  • ByteArrayOutputStream Package 字节数组,以便将其用作输出流。
  • 使用DatatypeConverter将字节数组转换为base64字符串,在核心Java 6之后,不需要额外的库

范例

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

zysjyyx43#

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/oaCwqo4GFAREVRUdMDWwTgcCopOB6VNlEFXRySD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