Fabric.js canvas.toDataURL()由Ajax发送给PHP

rod*_*ini 5 javascript php canvas fabricjs

当我需要创建一个透明背景的图像时,我遇到了问题.我仍然不知道问题是使用fabricjs还是使用php.当我发送带有彩色背景的图像时,一切正常.发送带透明背景的图像时会出现问题.生成的图像使用黑色背景创建.所以,让我解释一下:当用户点击"保存"按钮时,我将画布的字符串表示发送到服务器端的php,以生成画布的图像.所以我使用follow函数通过Ajax发送画布的字符串表示形式(jQuery的POST函数):


    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.");
            }
        });
    }

在PHP文件中我使用以下代码生成图像:


    // 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';
    }

同样,问题只在于背景透明画布.彩色背景一切正常.

gol*_*les 1

我不知道这是否正是您遇到的问题,但 GD 库的某些imagecreate*函数创建的图像没有 alpha 通道。

我发现的解决方法是使用创建图像imagecreatetruecolor并将透明图像复制到其上。

尝试这样的过程:

$img = imagecreatefromstring($data);
$w = imagesx($img);
$h = imagesy($img);
$alpha_image = imagecreatetruecolor( $w, $h );
imagecopyresampled( $alpha_image, $img, 0, 0, 0, 0, $w, $h, $w, $h );
Run Code Online (Sandbox Code Playgroud)

这应该确保您最终得到具有正确 Alpha 通道的“真彩色”图像。