1

我有一个项目,我需要使用 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);
4

1 回答 1

2

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

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

$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);
于 2013-04-22T11:47:45.567 回答