In PHP, the GD library is a powerful tool for processing images, which supports the creation, modification, and synthesis of multiple image formats. In practical applications, sometimes we need to read the image from the existing GD2 image file and then draw lines, text, shapes, etc. on it. This article will introduce in detail how to use imagecreatefromgd2() to load .gd2 format images and combine imagecolorallocate() for graphical drawing.
.gd2 is an image format dedicated to the GD library, which supports compressed and uncompressed data, suitable for fast loading and processing. Although this is not a common image format for web pages (such as JPEG, PNG), it is useful in server-side image processing.
imagecreatefromgd2(string $filename)
Create image resources from a .gd2 file. Returns a GD image resource handle.
imagecolorallocate(resource $image, int $red, int $green, int $blue)
Assign a color to the image and return the identifier of that color.
Other commonly used functions such as imageline() , imageellipse() , and imagestring() can be used to draw graphics or add text.
Here is a complete PHP example showing how to load a .gd2 file and draw a graph (red lines and blue ellipse) on the image, with the final output as a PNG image.
<?php
// set up GD2 File path(Make sure this file exists)
$gd2_file = 'https://m66.net/images/sample.gd2';
// Download remote GD2 File to local temporary file(GD2 Direct reading is not supported URL)
$temp_file = tempnam(sys_get_temp_dir(), 'gd2');
file_put_contents($temp_file, file_get_contents($gd2_file));
// from GD2 File creation image resources
$image = imagecreatefromgd2($temp_file);
if (!$image) {
die('Unable to create image resources,Check, please GD2 Is the file valid?。');
}
// Assign colors to images
$red = imagecolorallocate($image, 255, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);
// Draw a straight red line on the image
imageline($image, 10, 10, 200, 200, $red);
// Draw a blue ellipse
imageellipse($image, 150, 100, 100, 50, $blue);
// set up输出为 PNG image
header('Content-Type: image/png');
imagepng($image);
// Free up resources
imagedestroy($image);
unlink($temp_file);
?>
imagecreatefromgd2() cannot read the URL directly, so you need to download the file first and save it as a local temporary file.
The GD2 image must be in a valid format or the loading will fail.
The correct Content-Type header must be set before outputting the image.
It is recommended to use PNG, JPEG and other formats to output, because the browser does not support direct rendering.gd2 .
Image watermarking system: dynamically add an identification or date to existing images on the server side.
Image editing platform: The images uploaded by users can be temporarily saved in .gd2 format and marked on it.
Data visualization: Draw data graphics according to background logic.