使用PHP从画布中保存图像,没有黑色背景
Save image from Canvas using PHP without black background
我有一个项目,我需要从用户使用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);
相关文章:
- 将画布转换为pdf:黑色背景
- DT数据表背景颜色为黑色,但仍有悬停和选择颜色
- 黑色三件套帆布背景
- 将画布对象另存为图像-黑色背景
- 滚动界面CSS-更改黑色背景上的颜色
- 嵌入视频,将黑色背景更改为自定义图像或第一个视频场景
- 带有黑色禁用背景的引导模态显示
- 根据十六进制背景获得白色/黑色
- 如何在黑色背景下进行揭示
- 有没有什么方法可以删除副标题'IPHONE上的黑色背景
- 黑色背景拉力赛图表
- 了解HTML5视频何时可以在没有黑色背景的情况下播放的事件
- 如何添加背景和文字的颜色分别为白色和黑色的导航在引导时,它被点击
- 背景渐变为黑色,点击按钮.未知的错误
- 如何从黑色背景更改背景颜色
- 使用PHP从画布中保存图像,没有黑色背景
- 当点击黑色背景外时,关闭弹出时事通讯表单
- 透明背景变成黑色后转换为webp格式通过HTML5画布
- JSPDF添加黑色背景转换PDF
- JavaScript - gallery - lighbtox -只有一半的屏幕变成黑色的背景