使用GD和PHP向透明图像添加背景色
来源:网络分享
编辑:引流技巧
时间:2026-05-10

最近在复习用PHP直接生成图片,本博客之前的栏目文档缩略图就是直接PHP合成的,这里贴出部分代码,以便方便自己后续有用到的时候可以直接拿来用。
话不多说,代码如下:
<?php $filePath = ''; //png的完整路径,包括文件名和扩展名 $savePath = ""; //保存的png的完整路径,包括文件名和扩展名 $colorRgb = array('red' => rand(50,200), 'green' => rand(50,200), 'blue' => rand(50,200)); //背景色 $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); //另存为图片文件 // imagejpeg($backgroundImg, $savePath, 90); //直接输出 header('Content-Type: image/jpeg'); imagejpeg($backgroundImg);

相关文章:
相关推荐:
栏目分类

最新文章

热门文章


