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?