PHP | imagesetpixel() Function

The imagesetpixel() function is an inbuilt function in PHP which is used to draw a pixel at the specified coordinate.
Syntax:
bool imagesetpixel( resource $image, int $x, int $y, int $color )
Parameters: This function accept four parameters as mentioned above and described below:
- $image: It specifies the image resource to work on.
- $x: It specifies the x-coordinate of pixel.
- $y: It specifies the y-coordinate of pixel.
- $color: It specifies the color of pixel.
Return Value: This function returns TRUE on success or FALSE on failure.
Below given programs illustrate the imagesetpixel() function in PHP:
Program 1 (Drawing a line on a image):
php
<?php // Load the png image $image = imagecreatefrompng( // Draw a line using imagesetpixel $red = imagecolorallocate($image, 255, 0, 0); for ($i = 0; $i < 1000; $i++) { imagesetpixel($image, $i, 100, $red); } // Output image to the browser header('Content-type: image/png'); imagepng($image); ?> |
Output:
Program 2 (Drawing a pattern):
php
<?php // Create a blank image 700x200 $image = imagecreatetruecolor(700, 200); $points = [ array('x' => 00, 'y' => 10), array('x' => 0, 'y' => 190), array('x' => 800, 'y' => 190) ]; // Prepare the color $green = imagecolorallocate($image, 0, 255, 0); // Draw the pattern $x = 700; $y = 200; for ($i = 0; $i < 100000; $i++) { imagesetpixel($image, round($x), round($y), $green); $a = rand(0, 2); $x = ($x + $points[$a]['x']) / 2; $y = ($y + $points[$a]['y']) / 2; } // Show the output in browser header('Content-Type: image/png'); imagepng($image); ?> |
Output:
Reference: https://www.php.net/manual/en/function.imagesetpixel.php




