Current Location: Home> Latest Articles> How to Use imagegif() with imagecreate() to Create and Output GIF Images?

How to Use imagegif() with imagecreate() to Create and Output GIF Images?

gitbox 2025-09-12
<?php
// This document is generated by PHP script
header("Content-Type: text/html; charset=utf-8");
?>
<hr>
<h1>How to Use imagegif() with imagecreate() to Create and Output GIF Images?</h1>
<p>In PHP's image processing extension GD library, <code>imagecreate()

Where $width and $height represent the width and height of the image. Once successfully created, you can draw on this canvas.

2. imagecolorallocate() to Allocate Colors

After creating the canvas, we need to allocate colors for the image. The imagecolorallocate() function is used to create a color in the image, with the syntax:

<span class="fun">int imagecolorallocate( resource $image , int $red , int $green , int $blue )</span>

For example, imagecolorallocate($img, 255, 0, 0) creates the color red in the image.

3. imagegif() to Output the Image

The imagegif() function is responsible for outputting the image in GIF format. It can either be directly displayed in the browser or saved as a file. The syntax is:

<span class="fun">bool imagegif( resource $image [, string $filename ] )</span>

If the $filename parameter is omitted, the image is directly output to the browser.

4. Example Code

Here’s an example demonstrating how to use imagecreate() and imagegif() to create a simple GIF image:

<?php
// Inform the browser that the output is a GIF image
header("Content-Type: image/gif");

// Create a 200x100 canvas
$img = imagecreate(200, 100);

// Allocate background color (white)
$white = imagecolorallocate($img, 255, 255, 255);

// Allocate drawing color (blue)
$blue = imagecolorallocate($img, 0, 0, 255);

// Write text on the canvas
imagestring($img, 5, 50, 40, "Hello GIF", $blue);

// Output as GIF format
imagegif($img);

// Free resources
imagedestroy($img);
?>

5. Conclusion

By using imagecreate() to create the canvas, imagecolorallocate() to allocate colors, and imagegif() to output the image, you can easily generate GIF images. This method is commonly used for generating CAPTCHA images, dynamic charts, or any other scenarios where images need to be generated dynamically.