imagecolortransparent函数在不同图片格式中的应用

PHP
389
2024/9/8 9:31:41
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

imagecolortransparent() 函数是 PHP 的 GD 库中的一个函数,用于设置 PNG 或 GIF 图像的透明色

以下是 imagecolortransparent() 函数在不同图片格式中的应用示例:

  1. PNG 图像:
// 创建一个宽度为 200、高度为 200 的真彩色图像
$image = imagecreatetruecolor(200, 200);

// 为图像分配颜色
$white = imagecolorallocate($image, 255, 255, 255);
$red = imagecolorallocate($image, 255, 0, 0);

// 使用白色填充背景
imagefill($image, 0, 0, $white);

// 绘制一个红色矩形
imagerectangle($image, 50, 50, 150, 150, $red);

// 将白色设置为透明色
imagecolortransparent($image, $white);

// 输出 PNG 图像
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
  1. GIF 图像:
// 创建一个宽度为 200、高度为 200 的调色板图像
$image = imagecreate(200, 200);

// 为图像分配颜色
$white = imagecolorallocate($image, 255, 255, 255);
$red = imagecolorallocate($image, 255, 0, 0);

// 使用白色填充背景
imagefill($image, 0, 0, $white);

// 绘制一个红色矩形
imagerectangle($image, 50, 50, 150, 150, $red);

// 将白色设置为透明色
imagecolortransparent($image, $white);

// 输出 GIF 图像
header("Content-type: image/gif");
imagegif($image);
imagedestroy($image);

在这两个示例中,我们首先创建了一个宽度为 200、高度为 200 的图像(一个真彩色图像和一个调色板图像)。然后,我们为图像分配了白色和红色。接下来,我们使用白色填充背景,并绘制了一个红色矩形。最后,我们将白色设置为透明色,并输出 PNG 或 GIF 图像。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: php strtotime函数的作用是什么