Javascript – Fabric.js canvas.toDataURL() sent to PHP by Ajax

canvasfabricjsjavascriptPHP

I have a problem here when I need create a image with transparent background. I still don´t know if the problem is with fabricjs or with php. Everything works fine when I sent a image with colored background. The problem occurs when I send a image with transparent background.
The generated image is created with black background.
So, let me explain better:
When the user click in save button, I´m sending the string representation of the canvas to php in the server-side, to be generated the image of the canvas. So I´m using the follow function to sending the string representation of the canvas by Ajax (POST function of jQuery):


    function sendStringRepresentation(){
        var strDataURI = canvas.toDataURL();
        strDataURI = strDataURI.substr(22, strDataURI.length);

        $.post("action/createImage.php",
        { 
            str: strDataURI
        },
        function(data){
            if(data == "OK"){
                $("#msg").html("Image created.");
        }
        else{
            $("#msg").html("Image not created.");
            }
        });
    }

In PHP file I´m using the follow code to generate the image:


    // createImage.php

    $data = base64_decode($_POST["str"]);

    $urlUploadImages = "../uploads/img/";
    $nameImage = "test.png";

    $img = imagecreatefromstring($data);

    if($img) {
        imagepng($img, $urlUploadImages.$nameImage, 0);
        imagedestroy($img);

        // [database code]

        echo "OK";
    }
    else {
        echo 'ERROR';
    }

Again, the problem is just with background transparent canvas. With colored background everything works fine.

Best Answer

The last step is quite the opposite:

imagecopyresampled( $img, $alpha_image, 0, 0, 0, 0, $w, $h, $w, $h );

And voila! The image is transparent!