PHP 将彩色像素替换为透明像素



我想以一种简单的方式制作一个带有透明背景的实心背景的徽标,所以我决定采用第一个像素并将所有图像上的颜色设置为透明,我知道这不是所有人的最佳解决方案,但我认为涵盖了大多数情况。

问题是像素是黑色而不是透明,这是我的代码:

$im = $this->loadImage($targetFile);
$this->replaceImageColor($im, imagecolorat($im, 0, 0), imageColorAllocateAlpha($im, 255, 255, 255, 127));
imagepng($im, 'test.png');

我的类函数:

function loadImage($imagePath) {
    $resource = false;
    if( strstr($imagePath, '.jpg') || strstr($imagePath, '.jpeg') )
        $resource = @imagecreatefromjpg($imagePath);
    if( strstr($imagePath, '.png') )
        $resource = @imagecreatefrompng($imagePath);
    return $resource;
}
function replaceImageColor($img, $from, $to) {
    // pixel by pixel grid.
    for ($y = 0; $y < imagesy($img); $y++) {
        for ($x = 0; $x < imagesx($img); $x++) {
            // find hex at x,y
            $at = imagecolorat($img, $x, $y);
            // set $from to $to if hex matches.
            if ($at == $from) 
                imagesetpixel($img, $x, $y, $to);
        }
    }
}

最后我用这种方式解决了它

$im = $this->loadImage($targetFileIcon);
$out = $this->transparentColorImage($im, imagecolorat($im, 0, 0));
imagepng($out, 'test.png');
imagedestroy($im);
imagedestroy($out);
function loadImage($imagePath) {
    $resource = false;
    if( strstr($imagePath, '.jpg') || strstr($imagePath, '.jpeg') )
        $resource = @imagecreatefromjpg($imagePath);
    if( strstr($imagePath, '.png') )
        $resource = @imagecreatefrompng($imagePath);
    return $resource;
}
function transparentColorImage($img, $color) {
    // pixel by pixel grid.
    $out = ImageCreateTrueColor(imagesx($img),imagesy($img));
    imagesavealpha($out, true);
    imagealphablending($out, false);
    $white = imagecolorallocatealpha($out, 255, 255, 255, 127);
    imagefill($out, 0, 0, $white);
    for ($y = 0; $y < imagesy($img); $y++) {
        for ($x = 0; $x < imagesx($img); $x++) {
            // find hex at x,y
            $at = imagecolorat($img, $x, $y);
            // set $from to $to if hex matches.
            if ($at != $color)
                imagesetpixel($out, $x, $y, $at);
        }
    }
    return $out;
}

我创建了一个带有 alpha 通道且没有 alpha 混合的真实图像。

BR

最新更新