使用java将图像转换为base64

2022-01-21 00:00:00 image base64 java jsp servlets

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

I need to convert a image object to a base64 object so I can load it into the tag on my client side.

但是我似乎无法弄清楚如何解决这个问题.有没有人有一段我可以轻松使用的代码?

However I can't seem to figure out how to pull this off. Is there anyone who has a piece of code for this that I could use easily?

这就是我用来把外部图片链接变成图片对象的方法

This is what I use to turn the external image link into a image object

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

不确定我是否以正确的方式进行.

not sure if I'm going about this the correct way.

推荐答案

使用 Apache IOUtilsBase64:

Using Apache IOUtils and Base64:

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

相关文章