Johannes van Heerden Johannes van Heerden - 1 month ago 8
PHP Question

Saving a base 64 image creates a blank image in PHP

First here's my client side code:

$("#fileToUpload").on("change", function(){
var filesToUpload = document.getElementById("fileToUpload");
var file = filesToUpload.files[0];
var img = new Image(600,400);
var reader = new FileReader();
reader.onload = function(e){
img.src = e.target.result;
}
reader.readAsDataURL(file);

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
img.onload = function(){

canvas.width = 600;
canvas.height = 400;

ctx.drawImage(img,0,0,canvas.width,canvas.height);
}

var dataURL = canvas.toDataURL("image/jpg");

var data = new FormData();
data.append("image", dataURL);

var xhttp = new XMLHttpRequest;
xhttp.open("POST", "test.php", true);

xhttp.send(data);

})


And here's my php code:

$imageArr = explode(',', $_POST['image']);
$image = base64_decode($imageArr[1]);
file_put_contents('image.jpg',$image);


I'm resizing the image on the client side and then sending it as a data url to php to then be saved as an image.

When I save an image it creates a blank image on my server. BUT when I save another image without refreshing the page it saves the previous image in it's place and this time correctly. This is beyond me, can someone please shed some light?

Answer

You are sending the image before it is loaded. Your img.onload function is executed after xhttp.send(data). When you upload one more time it gets previous image which is already loaded.

Try following:

$("#fileToUpload").on("change", function(){
        var filesToUpload = document.getElementById("fileToUpload");
        var file = filesToUpload.files[0];
        var img = new Image(600,400);
        var reader = new FileReader();
        reader.onload = function(e){
            img.src = e.target.result;
        }
        reader.readAsDataURL(file);

        var canvas = document.getElementById("canvas");
        canvas.width = 600;
        canvas.height = 400;
        var ctx = canvas.getContext('2d');

        img.onload = function(){

            ctx.drawImage(img,0,0,canvas.width,canvas.height);

            var dataURL = canvas.toDataURL("image/jpg");

            var data = new FormData();
            data.append("image", dataURL);

            var xhttp = new XMLHttpRequest;
            xhttp.open("POST", "test.php", true);

            xhttp.send(data);
        }

    })