Replace the specific RGB color with another image using PHP

前端 未结 1 1587
失恋的感觉
失恋的感觉 2021-02-20 01:36

I derived a perfect color replace script from https://stackoverflow.com/a/32710756/1620626. I want to replace the target color with the image background. The original image is b

相关标签:
1条回答
  • 2021-02-20 02:20

    You can just read two images, source and background, and take pixels from background image and set to the source.

    Below is the last part of your code above which shows this idea:

    $filename = 'images/01.png';
    $bgFilename = 'images/background.png';
    $im = imagecreatefrompng($filename);
    $bg = imagecreatefrompng($bgFilename);
    $out = imagecreatetruecolor(imagesx($im), imagesy($im));
    $transColor = imagecolorallocatealpha($out, 254, 254, 254, 127);
    imagefill($out, 0, 0, $transColor);
    
    for ($x = 0; $x < imagesx($im); $x++) {
        for ($y = 0; $y < imagesy($im); $y++) {
            $pixel = imagecolorat($im, $x, $y);
            $bgPixel = imagecolorat($bg, $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])){
                // Instead of taking the replacementColor
                /* $color = HSLtoRGB($replacementColor[0], $replacementColor[1], $colorHSL[2]); */
                /* $red = $color[0]; */
                /* $green= $color[1]; */
                /* $blue = $color[2]; */
                // We just take colors from the backround image pixel
                $red = ($bgPixel >> 16) & 0xFF;
                $green = ($bgPixel >> 8) & 0xFF;
                $blue = $bgPixel & 0xFF;
            }
    
            if ($alpha == 127) {
                imagesetpixel($out, $x, $y, $transColor);
            }
            else {
                imagesetpixel($out, $x, $y, imagecolorallocatealpha($out, $red, $green, $blue, $alpha));
            }
        }
    }
    imagecolortransparent($out, $transColor);
    imagesavealpha($out, TRUE);
    header('Content-type: image/png');
    imagepng($out);
    

    The result can look like this:

    0 讨论(0)
提交回复
热议问题