In PHP, the GD library provides a series of powerful image processing functions, where imagecreatefromgd2 is an important function for loading .gd2 format images. The GD2 format is an image format designed for fast loading and high compression rates. Although it is not as frequent as JPEG or PNG, it is very useful in specific scenarios.
This article will introduce how to use the imagecreatefromgd2 function to read a GD2 image, analyze the color of each pixel, modify a specific color area, and save the image as a new file.
First, you need an image file in .gd2 format. You can save existing images to GD2 format through the GD library as follows:
<?php
$image = imagecreatefrompng('example.png');
imagegd2($image, 'example.gd2');
imagedestroy($image);
?>
<?php
$gdImage = imagecreatefromgd2('example.gd2');
if (!$gdImage) {
die('Unable to load GD2 image');
}
?>
We can get the width and height of the image through imagesx() and imagesy() , and then iterate through each pixel point to read the color value using imagecolorat() .
<?php
$width = imagesx($gdImage);
$height = imagesy($gdImage);
for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
$rgb = imagecolorat($gdImage, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
// Example:If the color is close to white,Modified to blue
if ($r > 200 && $g > 200 && $b > 200) {
$newColor = imagecolorallocate($gdImage, 0, 0, 255);
imagesetpixel($gdImage, $x, $y, $newColor);
}
}
}
?>
After the modification is completed, we can save the processed image as a new PNG or GD2 file, or directly output it to the browser:
<?php
// Save as new GD2 document
imagegd2($gdImage, 'modified.gd2');
// Or save as PNG
imagepng($gdImage, 'modified.png');
// Clean the memory
imagedestroy($gdImage);
?>
imagecolorallocate() every time the color is allocated, it may cause color resources to be duplicated. For optimization, common colors can be pre-allocated.
GD2 files are optionally compressed and directory structured. For more advanced options, please refer to the PHP manual.
You can download the sample file on your server at the following address (please replace it according to your own path):