user72003 user72003 - 1 month ago 16
Java Question

Java BufferedImage to PNG format Base64 String

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

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");