使用PHP在没有黑色背景的情况下从Canvas保存图像

时间:2013-04-22 11:40:35

标签: php javascript canvas

我有一个项目需要使用php从用户绘制的画布保存图像。问题是当我希望默认为白色或透明时,保存的文件总是有黑色背景。

我尝试在画布上绘制白色填充,但是当在画布上进行交互时,sketch.js会将其删除。

JS

function saveImage(){
    var xmlhttp;
    xmlhttp=((window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"));
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            //do something with the response
        }
    }
    xmlhttp.open("POST","upload.php",true);
    var oldCanvas = document.getElementById('colors_sketch').toDataURL("image/png");
    var img = new Image();
    img.src = oldCanvas;
    xmlhttp.setRequestHeader("Content-type", "application/upload")
    xmlhttp.send(oldCanvas);
}

PHP

$im = imagecreatefrompng($GLOBALS["HTTP_RAW_POST_DATA"]);

imagepng($im, 'filename.png');

我已根据建议对其进行了修改,但似乎无法保存

$filePath = '($GLOBALS["HTTP_RAW_POST_DATA"])';  
$savePath = 'filename.png';  //full path to saved png, including filename and extension
$colorRgb = array('red' => 255, 'green' => 0, 'blue' => 0);  //background color

$img = @imagecreatefrompng($filePath);
$width  = imagesx($img);
$height = imagesy($img);


$backgroundImg = @imagecreatetruecolor($width, $height);
$color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'],                 $colorRgb['blue']);
imagefill($backgroundImg, 0, 0, $color);


imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height);


imagepng($backgroundImg, $savePath, 0);

1 个答案:

答案 0 :(得分:1)

您需要在 PHP 中添加不在Canvas中的背景。

查看this解决方案。主要关键是创建带背景的图像:

$backgroundImg = @imagecreatetruecolor($width, $height);
$color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'], $colorRgb['blue']);
imagefill($backgroundImg, 0, 0, $color);

将图像复制到其上:

imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height);