如何使用 PHP 中的 imagesetpixel() 函数设置单个像素?
phpserver side programmingprogramming
imagesetpixel() 是 PHP 内置函数,用于在指定的坐标处设置单个像素。
语法
bool imagesetpixel(resource $image, int $x, int $y, int $color)
参数
imagesetpixel() 接受四个参数:$image、$x、$y 和 $color。
$image − 指定要处理的图像资源。
$x − 指定像素的 x 坐标。
$y − 指定像素的 y 坐标。
$color − 指定像素的颜色。
返回值 −
imagesetpixel() 成功时返回 True,失败时返回 False。
示例 1
<?php // 使用 imagecreatefromjpeg() 函数加载 png 图像 $img = imagecreatefromjpeg('C:\xampp\htdocs\test\29.jpg'); // 使用 imagesetpixel() 函数绘制线条 $blue = imagecolorallocate($img, 255, 255, 0); for ($i = 0; $i < 1000; $i++) { imagesetpixel($img, $i, 100, $blue); } // 将输出图像显示到浏览器 header('Content-type: image/png'); imagepng($img); ?>
输出
示例 2
<?php $x = 700; $y = 300; $gd = imagecreatetruecolor($x, $y); $corners[0] = array('x' => 100, 'y' => 10); $corners[1] = array('x' => 0, 'y' => 170); $corners[2] = array('x' => 190, 'y' => 170); $blue = imagecolorallocate($gd, 255, 0, 0); for ($i = 0; $i < 100000; $i++) { imagesetpixel($gd, round($x),round($y), $blue); $a = rand(0, 2); $x = ($x + $corners[$a]['x']) / 2; $y = ($y + $corners[$a]['y']) / 2; } header('Content-Type: image/png'); imagepng($gd); ?>