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