PHP GD:合并模糊的矩形

时间:2016-02-24 17:41:48

标签: php gd

我需要在另一个图像(白色矩形)上合并模糊的矩形。我尝试imagesavealpha(),但不幸的是矩形的背景仍然是黑色的,我希望它具有从红色到白色的渐变。

这是我的代码:

<?php
$width = 200;
$height = 180;

$bw = $bh = 30;

$img1 = imagecreatetruecolor($width, $height);
$img2 = imagecreatetruecolor($width, $height);

$white = imagecolorallocate($img1, 255, 255, 255);
$red = imagecolorallocate($img2, 255, 0, 0);
imagefilledrectangle($img1, 0, 0, 100, 100, $white);
imagefilledrectangle($img2, 5, 5, 25, 25, $red);

imagefilter($img2, IMG_FILTER_GAUSSIAN_BLUR);
imagefilter($img2, IMG_FILTER_GAUSSIAN_BLUR);
imagefilter($img2, IMG_FILTER_GAUSSIAN_BLUR);
imagefilter($img2, IMG_FILTER_GAUSSIAN_BLUR);
imagefilter($img2, IMG_FILTER_GAUSSIAN_BLUR);

imagesavealpha($img2, true);

imagecopymerge($img1, $img2, 20, 20, 0, 0, $bw, $bh, 100);

header('Content-Type: image/png');
imagepng($img1);

imagedestroy($img1);

结果图片是:

enter image description here

1 个答案:

答案 0 :(得分:2)

如果您只想在白色背景上使用模糊的红色矩形,则可以将代码简化为:

<?php
$width = 200;
$height = 180;

$img = imagecreatetruecolor($width, $height);

// fill with opaque white.
imagefill($img, 0, 0, 0x00ffffff);

// draw rectangle in opaque red.
imagefilledrectangle($img, 5, 5, 25, 25, 0x00ff00000);

for ($i = 0; $i < 5; $i++) {
    imagefilter($img, IMG_FILTER_GAUSSIAN_BLUR);
}

header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);

结果(当然白色背景与页面背景混合......):

result

如果您希望能够将红色矩形与任何背景颜色(完全Alpha混合)混合,那么您可能会失败。据我所知,IMG_FILTER_GAUSSIAN_BLUR不支持alpha值(我使用PHP 7.0.3)。