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

后端 未结 3 1554
忘掉有多难
忘掉有多难 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:13

    Here's a working solution for PNG files:

    $filePath = '';  //full path to your png, including filename and extension
    $savePath = '';  //full path to saved png, including filename and extension
    $colorRgb = array('red' => 255, 'green' => 0, 'blue' => 0);  //background color
    
    $img = @imagecreatefrompng($filePath);
    $width  = imagesx($img);
    $height = imagesy($img);
    
    //create new image and fill with background color
    $backgroundImg = @imagecreatetruecolor($width, $height);
    $color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'], $colorRgb['blue']);
    imagefill($backgroundImg, 0, 0, $color);
    
    //copy original image to background
    imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height);
    
    //save as png
    imagepng($backgroundImg, $savePath, 0);
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题