Possible to add background color to transparent image using GD and PHP

后端 未结 3 1579
忘掉有多难
忘掉有多难 2021-01-14 01:38

I have the thumbnail creation class written with php language using GD. I want to know is when i upload the transparent image which is png or gif, can i be able to put backg

3条回答
  •  渐次进展
    2021-01-14 02:23

    Very simple code with dynamic background color.

    > 0x10);
                $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
                $rgbArray['blue'] = 0xFF & $colorVal;
            } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
                $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
                $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
                $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
            } else {
                return false; //Invalid hex color code
            }
            return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray;die;
        }
        $color_code = hex2RGB('#fff000');
    
        $imgName = uniqid();
        $filePath = 'old-img/clothing_type_test.png';  //full path to your png, including filename and extension
        $savePath = 'new-img/'.$imgName.'.png';  //full path to saved png, including filename and extension
        $colorRgb = array('red' => $color_code['red'], 'green' => $color_code['green'], 'blue' => $color_code['blue']);  //background color
    
        $img = @imagecreatefrompng($filePath);
        $width  = imagesx($img);
        $height = imagesy($img);
    
        $backgroundImg = @imagecreatetruecolor($width, $height);
        $color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'], $colorRgb['blue']);
        imagefill($backgroundImg, 0, 0, $color);
        imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height);
        imagepng($backgroundImg, $savePath, 0);
    ?>
    

提交回复
热议问题