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

拈花ヽ惹草 提交于 2019-12-03 03:42:26

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!

Why did you use GD for this? You can use file_put_contents for save png file from your canvas.

// createImage.php

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

$urlUploadImages = "../uploads/img/test.png";
file_put_contents($urlUploadImages, $data);

I don't know if this is exactly the problem you're experiencing, but some of the GD library's imagecreate* functions create images without the alpha channel.

The workaround I've found is to create an image using imagecreatetruecolor and copy your transparent image onto it.

Try a process like this:

$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 );

That should ensure that you end up with a "true color" image with the proper alpha channel.

JPG toDataURL transforms transparent background to black.

I had the exact same problem and added this
imageAlphaBlending($img, true);
imageSaveAlpha($img, true);

to rodrigopandini's code and it works perfect now.:)

 // createImage.php

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

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

      $img = imagecreatefromstring($data);

      imageAlphaBlending($img, true);
      imageSaveAlpha($img, true);

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

    // [database code]

    echo "OK";
    }
     else {
          echo 'ERROR';
          }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!