Skip to content
PHP Logo

What is the function imagesetpixel used for in PHP?

The function imagesetpixel in PHP is used to set the color of a single pixel in an image resource. This function takes the image resource, x and y coordinates of the pixel, and the color value as parameters. By using imagesetpixel, you can manipulate individual pixels in an image to create effects, draw shapes, or modify specific areas of an image.

php
// Create a blank image with a white background
$width = 200;
$height = 200;
$image = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);

// Set a pixel at coordinates (100, 100) to red
$red = imagecolorallocate($image, 255, 0, 0);
imagesetpixel($image, 100, 100, $red);

// Output the image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);