Replace image Green Background with php image GD

时间:2018-06-04 17:33:34

标签: php image gd transparent

Hello I need to replace green image background to transparent can someone help me here please

this is my code

/* ---------------CHANGE THESE------------------- */
$colorToReplace = RGBtoHSL(0, 255, 0);
$hueAbsoluteError = 40;
$replacementColor = RGBtoHSL(255, 255, 255);
/* ---------------------------------------------- */

$filename = $path.$file;
$im = imagecreatefrompng($filename);
$out = imagecreatetruecolor(imagesx($im), imagesy($im));
$transColor = imagecolorallocatealpha($out, 0, 0, 0, 0);
imagefill($out, 0, 0, $transColor);

for ($x = 0; $x < imagesx($im); $x++) {
for ($y = 0; $y < imagesy($im); $y++) {
    $pixel = imagecolorat($im, $x, $y);

    $red = ($pixel >> 16) & 0xFF;
    $green = ($pixel >> 8) & 0xFF;
    $blue = $pixel & 0xFF;
    $alpha = ($pixel & 0x7F000000) >> 24;

    $colorHSL = RGBtoHSL($red, $green, $blue);

    if ((($colorHSL[0]  >= $colorToReplace[0] - $hueAbsoluteError) && ($colorToReplace[0] + $hueAbsoluteError) >= $colorHSL[0])){
        $color = HSLtoRGB($replacementColor[0], $replacementColor[1], $colorHSL[2]);
        $red = $color[0];
        $green= $color[1];
        $blue = $color[2];
    }

    if ($alpha == 127) {
        imagesetpixel($out, $x, $y, $transColor);
    }
    else {
        imagesetpixel($out, $x, $y, imagecolorallocatealpha($out, $red, $green, $blue, 0));
    }
}
}

imagecolortransparent($out, $transColor);
imagesavealpha($out, TRUE);
header('Content-type: image/png');
imagepng($out);

i want to remove green background to transparent from this image before but i got result like this image after

how to fix this

thankyou

0 个答案:

没有答案