【发布时间】:2015-11-22 20:04:05
【问题描述】:
我使用org.apache.axis.encoding.Base64 类将图像编码为base64。我的代码:
public String get64EncodedPhotoForUser(User user) {
// Path to image
String path = "some path to the jpg file on the server";
// Read image from server
String base64Image = null;
try {
BufferedImage bufferedImage = ImageIO.read(new File(path));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
base64Image = Base64.encode(imageInByte);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return base64Image;
}
如您所见,我首先将图像转换为字节数组,因为这是编码方法所期望的。一切似乎都工作正常,我得到了我的编码字符串,它似乎是一个正确编码的字符串。值得一提的是,一些在线解码器可以正确解码图像,而另一些则不能,我认为这很奇怪..
当我尝试在我的 HTML 中显示图像时:
<img ng-src="data:image/png;base64,/9j/4AAQSkZJRgABAgAAA..." id="avatar">
它不起作用。当您将 html 指向不存在的图像时,我会看到“缺少图像”图标。
我已将编码字符串复制并粘贴到 jsfiddle 中,您可以查看 here
PS - 我还采用 base64 字符串,并将它与其他一些东西一起以 JSON 对象的形式从服务器传递到客户端。您在 jsfiddle 中看到的 Base64 字符串是我在客户端返回的。是不是编码的字符串在通过网络传递时可能已被损坏或修改?
【问题讨论】:
-
快速问题:从在 Java 中输出 base 64 编码字符串到创建 Fiddle,您采取了哪些步骤?这是将最终字符转换为显式 unicode 的地方。
-
我基本上采用该编码字符串,将其设置为我创建的“用户”POJO 的属性,然后使用 Gson (github.com/google/gson) 将该用户 POJO 转换为 JSON 对象,然后我使用 HttpServletResponse 发送到客户端,将内容类型设置为“text/json”
标签: java html image encoding base64