Search code examples
phppnggd

Apply background to PNG transparent image after GD IMG_FILTER_COLORIZE


I have transparent png image (it's monochrome) and I apply the colourise php GD filter. So now its in colour, but I am having trouble applying a white background to get rid of transparency.

    list($r,$g,$b) = array_map('hexdec',str_split($ColourPrimary,2));
    $r = $r - 52;
    $g = $g - 52;
    $b = $b - 52;

    imagesavealpha($im, true);
    imagefilter($im, IMG_FILTER_COLORIZE, $r, $g, $b);

    $bw  = imagesx($im);
    $bh = imagesy($im);
    $background = imagecreatetruecolor($bw,$bh);
    $bkwhite = imagecolorallocate($background, 255, 255, 255);
    imagefill($background,0,0,$bkwhite);
    imagecopy($background, $im, 0, 0, 0, 0, $bw, $bh);

Solution

  • after a good night sleep I realised I was doing it backwards. I applied background first and copied image on top.

        list($r,$g,$b) = array_map('hexdec',str_split($ColourPrimary,2));
        $r = $r - 52;
        $g = $g - 52;
        $b = $b - 52;
    
        $imfore = imagecreatefrompng(FILELOCATION);
        imagesavealpha($imfore, true);
        imagefilter($imfore, IMG_FILTER_COLORIZE, $r, $g, $b);
        $bw  = imagesx($imfore);
        $bh = imagesy($imfore);
    
        $im = imagecreatetruecolor($bw,$bh);
        $bkwhite = imagecolorallocate($im, 255, 255, 255);
        imagefill($im,0,0,$bkwhite);
        imagecopy($im, $imfore, 0, 0, 0, 0,$bw,$bh);