GD Library - Create Transparent Image

This section provides a tutorial example on how to create an image with transparent background using GD Library functions.

If you want to create an image with a transparent background with the GD Library, here is what you need to remember:

1. Select a color for the background of the image. Make sure this background color is not used to draw any graphical element on the image.

2. Fill the entire image with the background color using imagefilledrectangle().

3. Draw all graphical elements on the image using imageline(), imageRectangle(), etc.

4. Set the background color to be transparent using imagecolortransparent().

5. Save the image in a format that supports transparent background like GIF or PNG.

Below is a PHP script that creates transparent background image in PNG format.

<?php
#  GD-Create-Transparent-Image.php
#- Copyright 2009 (c) HerongYang.com. All Rights Reserved.

$image = imagecreatetruecolor(400,400);

$blue = imagecolorallocate($image, 0, 0, 255);
$green = imagecolorallocate($image, 0, 255, 0);
$red = imagecolorallocate($image, 255, 0, 0);
$black = imagecolorallocate($image, 0, 0, 0);

print("Fill the background...\n");
$bgColor = $black;
imagefilledrectangle($image, 0, 0, 400, 400, $bgColor);

print("Drawing some graphics...\n");
imagefilledrectangle($image, 50, 50, 350, 350, $blue);
imagefilledellipse($image, 200, 200, 200, 200, $green);

print("Open a circle to see the background...\n");
imagefilledellipse($image, 200, 200, 100, 100, $bgColor);

print("Set the background to be transparent...\n");
imagecolortransparent($image, $bgColor);

$file = "GD-Transparent-Graphics.png";
imagepng($image, $file);
print("Image saved:\n");
print("   File: $file\n");
?>

Run the above PHP script example:

php GD-Create-Transparent-Image.php

Fill the background...
Drawing some graphics...
Open a circle to see the background...
Set the background to be transparent...
Image saved:
   File: GD-Transparent-Graphics.png

You should get an interesting transparent image.

Table of Contents

 About This Book

 Introduction and Installation of PHP

 Managing PHP Engine and Modules on macOS

 Managing PHP Engine and Modules on CentOS

 cURL Module - Client for URL

 DOM Module - Parsing HTML Documents

GD Module - Manipulating Images and Pictures

 GD Library of Image Functions

 GD Library - Draw Graphical Elements

 GD Library - Print 2 Pictures on 1 Page

GD Library - Create Transparent Image

 Transparent Image Over Text Web Page

 GD Library - Pad Transparent Image

 MySQLi Module - Accessing MySQL Server

 OpenSSL Module - Cryptography and SSL/TLS Toolkit

 PCRE Module - Perl Compatible Regular Expressions

 SOAP Module - Creating and Calling Web Services

 SOAP Module - Server Functions and Examples

 Zip Module - Managing ZIP Archive Files

 References

 Full Version in PDF/EPUB