I tried to give a working example of my code on JSFiddle, but I could only get the dataURL of the image to go into an input. (JS Fiddle: http://jsfiddle.net/dyt943s0/38/.) (EDIT: I was able to make a link that sends you to the DataURL image.)
Here is a copy of the corrupted image, (if you try opening in photoshop, it will not work, and gives the error: "Could not complete your request because the file-format module cannot parse the file"):
Or view http://mcgroup.freshfocuscrm.com/img/phot.png for a copy of the original photo.
Here is my JavaScript code (as it is on my actual web page):
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="../../ffm.freshfocuscrm.com/Driving Log/tmp/background-lines.png";
function start(){
var bottleCanvas = document.getElementById('bottleCanvas');
// var designCanvas = $("#chartContainer .canvasjs-chart-canvas").get(0);
var ctxb=bottleCanvas.getContext('2d');
//var ctxd=editorCanvas.getContext('2d');
ctxb.drawImage(img,0,0);
//ctxd.fillRect(5,5,5,5);
downloadCanvas();
}
function downloadCanvas() {
var bottleCanvas = document.getElementById('bottleCanvas');
var designCanvas = $("#chartContainer .canvasjs-chart-canvas").get(0);
var bottleContext = bottleCanvas.getContext('2d');
bottleContext.drawImage(designCanvas, 0, 0);
var dataURL = bottleCanvas.toDataURL("image/png");
console.log(dataURL);
$(".dataurl").val(dataURL);
$(".submit-create-pdf").click();
}
Then my PHP Code to download the image onto my server:
$img = $_POST['dataurl_image'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$fileName = 'photos.png';
file_put_contents(WEBSITE_URL.'/Driving Log/tmp/'.$fileName, $fileData);
However, I am almost sure that this is due to a PHP error, since if I put the DataURL code directly into my URL bar, and save the image manually, I can open it in PhotoShop. I just can't seem to figure out what that error is.
Some additional info:
The image seems to get created properly, for example, I can open it in Windows Photo Viewer and I can display it in an tag on my site.
If I open in MS Paint, and save the image, then the image becomes uncorrupted.
I have also tried using the following PHP code to create the image, which does not work either:
$image_url = $_POST['dataurl_image']; $image = @file_get_contents($image_url); $filename = 'uniqqid.png'; file_put_contents(WEBSITE_URL.'/Driving Log/tmp/'.$filename, $image);
The image was uncorrupted when I used the following JS code (instead of the one above):
var canvas = $("#chartContainer .canvasjs-chart-canvas").get(0); var dataURL = canvas.toDataURL('image/png'); console.log(dataURL); $("#btn-download").attr("href", dataURL); $(".dataurl").val(dataURL);
Also, please note: I am trying all of this code on my Localhost Wamp Server, if that makes a difference?
Thank you!