Pregunta

I'm using the following code to encode a java.awt.Image in Base64:

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).

I did some debugging and found out that bufferedImage at least has correct dimensions, but out only contains 308 bytes after executing ImageIO.write(...). This number increases with bigger images, but the characters keep being repetitive and too few.

Am I missing something?

¿Fue útil?

Solución

The code as shown in the question creates an empty BufferedImage, and PNG format encodes empty images pretty effectively.

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();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top