如何使用 imagecreatetruecolor() 在 PHP 中创建新的真彩色图像?

phpserver side programmingprogramming

imagecreatetruecolor() 是 PHP 中的内置函数,用于创建新的真彩色图像。它返回给定大小的空白图像。

语法

resource imagecreatetruecolor($width, $height)

参数

imagecreatetruecolor() 需要两个参数,$width$height

  • $width$width 参数用于设置图片宽度。

  • $height$height 参数用于设置图片高度。

返回值

imagecreatetruecolor() 成功时返回图片资源标识符,出错时返回 false。

示例 1

<?php
   // 设置多边形的顶点
   $values = array(
      150, 50, // 点 1 (x, y)
      50, 250, // 点 2 (x, y)
      250, 250 // 点 3 (x, y)
   );
   // 创建图像的大小或空白图像
   $image = imagecreatetruecolor(700, 350);

   // 设置图像的背景颜色
   $background_color = imagecolorallocate($image, 122, 122, 122);

   // 使用上面选择的颜色填充背景
   imagefill($image, 0, 0, $background_color);

   // 为多边形分配颜色
   $image_color = imagecolorallocate($image, 0, 255, 255);

   // 绘制多边形
   imagepolygon($image, $values, 3, $image_color);

   // 将图片输出到浏览器
   header('Content-type: image/png');

   imagepng($image);
?>

输出

示例 2 − 下面的 PHP 代码将创建一个新的 GD 图像流

<?php
   header ('Content-Type: image/gif');
   $img = @imagecreatetruecolor(550, 220)
   or die('Cannot Initialize new GD image stream');
   $text_color = imagecolorallocate($img, 255, 255, 0);
   
   imagestring($img, 10, 50, 50, 'A Simple PHP Example', $text_color);
   imagepng($img);
   imagedestroy($img);
?>

输出


相关文章