用背景颜色填充png透明度

时间:2018-09-21 14:37:25

标签: php gd php-gd

我正在重构大约5年前写的旧图像裁剪/调整大小库,但我一直试图恢复其功能之一。有趣的是,由于我可能从未真正使用过它,所以我什至不确定它是否可以在那时使用。

我需要能够在保持透明度(有效)的同时处理png图像,但是我也希望无法用颜色填充图像的透明部分。

创建一个空白图像并用一种颜色填充效果很好,但是当我尝试将png粘贴到其上时,背景再次透明。

这是我的代码的简化版本:

 <?php

$src = imagecreatefrompng($pathToSomePngFile);

imagealphablending($src, false);
imagesavealpha($src, true);

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

if ($backgroundColor) {
    $fillColor = imagecolorallocate(
        $output, 
        $backgroundColor['r'], 
        $backgroundColor['g'], 
        $backgroundColor['b']
    );

    imagefilledrectangle(
        $output, 
        0, 
        0, 
        $width, 
        $height, 
        $fillColor
    );
} else {
    imagealphablending($output, false);
    imagesavealpha($output, true);
}

imagecopyresampled(
    $output,
    $src,
    0,
    0,
    0,
    0,
    $width,
    $height,
    $width,
    $height
);

imagepng($output, $pathToWhereImageIsSaved);

更新

已更新delboy1978uk的解决方案,以使其在不更改我的其他设置的情况下正常工作。

1 个答案:

答案 0 :(得分:1)

类似的事情应该起作用。

<?php

// open original image
$img = imagecreatefrompng($originalTransparentImage);
$width  = imagesx($img);
$height = imagesy($img);

// make a plain background with the dimensions
$background = imagecreatetruecolor($width, $height);
$color = imagecolorallocate($background, 127, 127, 127); // grey background
imagefill($background, 0, 0, $color);

// place image on top of background
imagecopy($background, $img, 0, 0, 0, 0, $width, $height);

//save as png
imagepng($background, '/path/to/new.png', 0);
相关问题