PHP Modules Tutorials - Herong's Tutorial Examples - v5.18, by Herong Yang
GD Library - Pad Transparent Image
This section provides a tutorial example on how to pad the transparent background of to expand an image using GD Library functions.
If you want to pad 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. Create a new image with the padded size of the original image.
3. Fill the new image with the background color using imagefilledrectangle().
4. Copy the original image to the new image using imagecopy(). The transparent background color of the original image is not copied.
5. Set the background color of the new image to be transparent using imagecolortransparent().
6. Save the new image in a format that supports transparent background like GIF or PNG.
Below is a PHP script that pads a transparent background image by 10% at all 4 sides.
<?php # GD-Pad-Transparent-Image.php #- Copyright 2009 (c) HerongYang.com. All Rights Reserved. $factor = 10; # padding transparent background for 10% $pic = imagecreatefrompng($argv[1]); $w = imagesx($pic); $h = imagesy($pic); $padx = intval($factor*$w/100); $pady = intval($factor*$h/100); print("Create a new image in padded size...\n"); $image = imagecreatetruecolor($w+2*$padx, $h+2*$pady); print("Select gray as the background.\n"); print("Hope it is not used in the original image...\n"); $bgColor = imagecolorallocate($image, 127, 127, 127); imagefill($image, 0,0, $bgColor); print("Copy over the original image.\n"); imagecopy($image,$pic, $padx,$pady, 0,0, $w,$h); print("Set the background to be transparent...\n"); imagecolortransparent($image, $bgColor); $file = "GD-Padded-Transparent-Graphics.png"; imagepng($image, $file); print("Image saved:\n"); print(" File: $file\n"); ?>
Run the above PHP script example:
php GD-Pad-Transparent-Image.php GD-Transparent-Graphics.png Create a new image in padded size... Select gray as the background. Hope it is not used in the original image... Copy over the original image. Set the background to be transparent... Image saved: File: GD-Padded-Transparent-Graphics.png
You should get a padded transparent image.
Table of Contents
Introduction and Installation of PHP
Managing PHP Engine and Modules on macOS
Managing PHP Engine and Modules on CentOS
DOM Module - Parsing HTML Documents
►GD Module - Manipulating Images and Pictures
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