java Base64编码不工作
我使用以下代码在Base64中对java.awt.Image
进行编码:
private String asBase64(Image image) throws IOException {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "PNG", out);
byte[] bytes = out.toByteArray();
return Base64.encodeBytes(bytes);
}
但是返回的字符串有点错误:它似乎太小(在20KB文件上只有308个字符),中间包含大量重复字符(~200 ^ {CD2>}字符)。p>
我做了一些调试,发现bufferedImage
至少有正确的维度,但是out
在执行ImageIO.write(...)
之后只包含308个字节。这一数字随着图像的增大而增加,但角色不断重复,数量太少
我错过什么了吗
# 1 楼答案
问题中显示的代码创建了一个空
BufferedImage
,PNG格式非常有效地对空图像进行编码您可能希望它包含原始图像的副本: