php - 在 Alpha 混合图像上设置背景颜色
问题描述
像这样保存 alpha 混合图像时:
使用imagejpeg()和下面的代码,我得到一个黑色的背景。
$sourcePath = "<path to the image above>";
$destPath = "<path to where I want to store it>";
$image = imagecreatefrompng($sourcePath);
imagejpeg($image, $destPath, 85);
我最终得到一个黑色方块。这显然不是我需要的,背景应该是白色的。
我阅读了 alpha blending,用 PHP 中的 GD 函数尝试了几件事,但我无法完成。也许我应该在保存之前将图像复制到新图像,但我宁愿不这样做。
我的问题是: 使用 PHP GD 函数以适当的白色背景保存上述图像的最简单方法是什么?输出中不需要 alpha 混合,我想要的只是白色背景。
额外问题: 有没有办法检测图像是否具有 Alpha 通道?
解决方案
当我使用以下代码复制图像时,我设法做到了:
// start with the same code as in the question
$sourcePath = "<path to the image above>";
$destPath = "<path to where I want to store it>";
$image = imagecreatefrompng($sourcePath);
// get image dimensions
$width = imagesx($image);
$height = imagesy($image);
// create a new image with the same dimensions
$newImage = imagecreatetruecolor($width, $height);
// get white in the new image
$white = imagecolorallocate($newImage, 255, 255, 255);
// and fill the new image with that
imagefilledrectangle($newImage, 0, 0, $width, $height, $white);
// now copy the alpha blended image over it
imagecopy($newImage, $image, 0, 0, 0, 0, $width, $height);
// and finally the jpeg output
imagejpeg($newImage, $destPath, 85);
这确实解决了我的问题,但是真的需要这种复制吗?
我仍然无法检测图像是否具有 Alpha 通道。
推荐阅读
- javascript - 是否可以使用“HERE Maps API for JavaScript”以可接受的性能呈现邮政编码边界?
- scala - 在 lagom 框架中准备语句和绑定?
- javascript - 在作为对象一部分的每个数组元素上都有一个条件
- java - Java Mail Api 发送电子邮件失败
- android - 如何在 widnows 10 中运行 react native 应用程序?
- xcode - Xcode 控制台是黑色的
- android - 如何在颤动中获取当前路线名称?
- django - 如何实现多个过滤器?
- python - 在二叉搜索树中查找父节点
- haskell - 如何使用类型同义词重载运算符?