-1

I am trying to take a screenshot of a page using HTML2Canvas.

I am getting the binary in base64 using canvas.toDataURL() and I send it back to Java.

I use the following JavaScript code which executes when I click a button:

$("#take_screenshot_button").bind("click", function(){$("#container").html2canvas(
{
    allowTaint: true,
    letterRendering: true,
    onrendered: function(canvas)
    {
        $("#screenshot").val(canvas.toDataURL());
        setTimeout(function(){$("#take_screenshot_form").submit();}, 2000);
    }
});});

I get the content of "toDataURL()" on the JAVA side and I decode it from base64 and then I save it to "C:\image.png" using:

String screenshot = request.getParameterMap().get("screenshot")[0];
screenshot = screenshot.replaceAll("data:image/png;base64,", "");
screenshot = new Base64Security().decodeBase64(screenshot);
File file1 = new File("C:\\image.png");
file1.createNewFile();
FileWriter fw = new FileWriter(file1.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(screenshot);
bw.close();

When I open the image with the windows image viewer, however, the image is blank. It does not say anything like "the file is corrupted", and I can the dimensions of the image in the image properties, but the image is blank in image viewer. When I use "ImageIO.write()" to write the file again (just in case), ImageIO reads "C:\image.png", and it says

"Error reading PNG image data" casued by "java.util.zip.ZipException: invalid bit length repeat".

All the articles and blogs I read say, use "HTML2Canvas", get the screenshot with toDataURL(), remove "data:image/png;base64", and just save the file. Apparently it does not work. Maybe I am missing something.

Can anyone please help with this?

Harald K
  • 26,314
  • 7
  • 65
  • 111
Dimitrios Efthymiou
  • 535
  • 1
  • 5
  • 17

1 Answers1

0

This line:

screenshot = new Base64Security().decodeBase64(screenshot);

...does not work, because you are decoding the base64-encoded binary data to a String (screenshot is a String). This will corrupt the data, kind of like using FTP ascii mode for binary data.

I'm not familiar with the base64 library you are using, but if you can decode your base64-encoded data to a byte[], ByteBuffer or InputStream you should be fine. If not, switch to another base64-decoding library that does.

Also, you can not use a Writer to write binary data, as it is made to handle character data. Instead use an OutputStream directly.

Something like:

byte[] decoded = new Base64Security().decodeBase64ToBytes(screenshot);

OutputStream output = new FileOutputStream(file1);
try {
    output.write(decoded);
}
finally {
    output.close();
}
Harald K
  • 26,314
  • 7
  • 65
  • 111