【问题标题】:PHP replace a color pixel by a transparente onePHP用透明像素替换颜色像素
【发布时间】:2025-12-07 08:50:02
【问题描述】:

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

问题是它着色黑色的像素设置为透明,这是我的代码:

$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);
        }
    }
}

【问题讨论】:

标签: php image-processing gd alpha-transparency


【解决方案1】:

我终于这样解决了

$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

【讨论】: