在Alpha混合图像上设置背景颜色

问题描述 投票:0回答:1

保存像这样的alpha混合图像时:

enter image description here

使用imagejpeg(),使用下面的代码,我得到了黑色背景。

$sourcePath = "<path to the image above>";
$destPath = "<path to where I want to store it>";
$image = imagecreatefrompng($sourcePath);
imagejpeg($image, $destPath, 85);

我最后得到一个黑色正方形。显然这不是我所需要的,背景应该是白色的。

我读了alpha混合,用PHP中的GD函数尝试了几件事,但是我做不到。也许我应该在保存之前将图像复制到新图像,但我不希望这样做。

我的问题是: 使用PHP GD函数以适当的白色背景保存上述图像的最简单方法是什么?输出中不需要Alpha混合,我只需要一个白色背景。

奖金问题: 是否可以检测图像是否具有Alpha通道?

php image-processing gd alphablending
1个回答
0
投票

使用此代码复制图像时,我设法做到了:

// 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通道。

© www.soinside.com 2019 - 2024. All rights reserved.