简体   繁体   English

Base64 编码不起作用

[英]Base64 encoding not working

I'm using the following code to encode a java.awt.Image in 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);
}

But the returned String is somehow wrong: It seems to be too small (only 308 chars on a 20KB-file) and contains a big amount of repetitive characters in the middle (~200 A chars).但是返回的 String 有点错误:它似乎太小(20KB 文件中只有 308 个字符)并且中间包含大量重复字符(~200 个A字符)。

I did some debugging and found out that bufferedImage at least has correct dimensions, but out only contains 308 bytes after executing ImageIO.write(...) .我做了一些调试,发现了bufferedImage至少有正确的尺寸,但out仅包含执行后,308个字节ImageIO.write(...) This number increases with bigger images, but the characters keep being repetitive and too few.这个数字随着更大的图像而增加,但字符总是重复且太少。

Am I missing something?我错过了什么吗?

The code as shown in the question creates an empty BufferedImage , and PNG format encodes empty images pretty effectively.问题中显示的代码创建了一个空的BufferedImage ,PNG 格式非常有效地对空图像进行编码。

You probably intended it to contain a copy of the original image:您可能希望它包含原始图像的副本:

BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
        image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics graphics = bufferedImage.getGraphics();
graphics.drawImage( image, 0, 0, null);
graphics.dispose();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM