Java BufferedImage to PNG format Base64 String

user72003 picture user72003 · Aug 24, 2011 · Viewed 47.5k times · Source

I'm trying to get a screenshot output as a base64 encoded string but not getting very far. The code I have so far uses a Base64 library ( http://iharder.sourceforge.net/current/java/base64/ ):

    Robot robot = new Robot();
    Rectangle r = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize() );
    BufferedImage bi = robot.createScreenCapture(r);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    OutputStream b64 = new Base64.OutputStream(os);
    ImageIO.write(bi, "png", os);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.writeTo(b64);
    String result = out.toString("UTF-8");

Each time I run this, "result" is always an empty string but I don't understand why. Any ideas?

Note: I don't want to have to write the png to a file on disk.

Answer

Codo picture Codo · Aug 24, 2011

The following statement works in the wrong direction:

out.writeTo(b64);

It overwrites the Base 64 data with the empty byte array of out.

What's the purpose of out anyway? I don't think you need it.

Update:

And you write the image directly to os instead of writing through the Base 64 encoder.

The following code should work:

...
ByteArrayOutputStream os = new ByteArrayOutputStream();
OutputStream b64 = new Base64.OutputStream(os);
ImageIO.write(bi, "png", b64);
String result = os.toString("UTF-8");