How to add transparency to an image using GD
This is a PHP Class useful if you need to add transparency to an image. Have a look at the source code and the explanations below:
class.image.transparency.php
<?php
/*
---------------------------------------------------------------------------------------------
Credits: Bit Repository
Source URL: http://www.bitrepository.com/web-programming/php/image-transparency-with-gd.html
---------------------------------------------------------------------------------------------
*/
/* Image Transparency Class */
class Image_Transparency {
var $source_image;
var $pct;
var $new_image_name;
var $save_to_folder;
function make_transparent()
{
$info = GetImageSize($this->source_image);
$width = $info[0];
$height = $info[1];
$mime = $info['mime'];
// What sort of image?
$type = substr(strrchr($mime, '/'), 1);
switch ($type)
{
case 'jpeg':
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$new_image_ext = 'jpg';
break;
case 'png':
$image_create_func = 'ImageCreateFromPNG';
$image_save_func = 'ImagePNG';
$new_image_ext = 'png';
break;
case 'bmp':
$image_create_func = 'ImageCreateFromBMP';
$image_save_func = 'ImageBMP';
$new_image_ext = 'bmp';
break;
case 'gif':
$image_create_func = 'ImageCreateFromGIF';
$image_save_func = 'ImageGIF';
$new_image_ext = 'gif';
break;
case 'vnd.wap.wbmp':
$image_create_func = 'ImageCreateFromWBMP';
$image_save_func = 'ImageWBMP';
$new_image_ext = 'bmp';
break;
case 'xbm':
$image_create_func = 'ImageCreateFromXBM';
$image_save_func = 'ImageXBM';
$new_image_ext = 'xbm';
break;
default:
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$new_image_ext = 'jpg';
}
// Source Image
$image = $image_create_func($this->source_image);
$new_image = ImageCreateTruecolor($width, $height);
// Set a White & Transparent Background Color
$bg = ImageColorAllocateAlpha($new_image, 255, 255, 255, 127); // (PHP 4 >= 4.3.2, PHP 5)
ImageFill($new_image, 0, 0 , $bg);
// Copy and merge
ImageCopyMerge($new_image, $image, 0, 0, 0, 0, $width, $height, $this->pct);
if($this->save_to_folder)
{
if($this->new_image_name)
{
$new_name = $this->new_image_name.'.'.$new_image_ext;
}
else
{
$new_name = $this->new_image_name(basename($this->source_image)).'_transparent'.'.'.$new_image_ext;
}
$save_path = $this->save_to_folder.$new_name;
}
else
{
/* Show the image without saving it to a folder */
header("Content-Type: ".$mime);
$image_save_func($new_image);
$save_path = '';
}
// Save image
$process = $image_save_func($new_image, $save_path) or die("There was a problem in saving the new file.");
return array('result' => $process, 'new_file_path' => $save_path);
}
function new_image_name($filename)
{
$string = trim($filename);
$string = strtolower($string);
$string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
$string = ereg_replace("[ \t\n\r]+", "_", $string);
$string = str_replace(" ", '_', $string);
$string = ereg_replace("[ _]+", "_", $string);
return $string;
}
}
?>
How it works?
First, we need to get some information about the image. To determine this we’ll use GetImageSize(). This function returns an array with 5 elements. We need 3: width, height & mime type. The last one is helpful if we need to get the type of the image: jpeg, png, gif, bmp etc. We will use it to determine the function that will create a new image from our file/URL. For effectiveness, we will use the concept of variable functions. For example, if the image is a PNG, $image_create_func will be equal with ‘ImageCreateFromPNG’. Notice how it’s used in line 76:
// Source Image $image = $image_create_func($this->source_image);
After this, we will create a new true color image (with the same width & height as the original source image) using ImageCreateTrueColor(). By default this function creates an image with black background. We will fill it with a white & transparent background:
// Set a White & Transparent Background Color $bg = ImageColorAllocateAlpha($new_image, 255, 255, 255, 127); // (PHP 4 >= 4.3.2, PHP 5) ImageFill($new_image, 0, 0 , $bg);
The last function we need to use to complete this process it ImageCopyMerge():
// Copy and merge ImageCopyMerge($new_image, $image, 0, 0, 0, 0, $width, $height, $this->pct);
This function copies and merges part of an image. Since, every coordinate (x, y) is equal with 0 the whole source image will be placed over the new image with white background.
Finally, we will save the new image, if a save path is defined. If not we will output the image to the browser using the right header:
/* Show the image without saving it to a folder */
header("Content-Type: ".$mime);
Here’s an example of how you can use this class:
example.php
<?php
error_reporting (E_ALL ^ E_NOTICE);
include 'class.image.transparency.php';
$transparency = new Image_Transparency;
// range of transparency (from 1 to 100)
$transparency->pct = 60;
// Source Image
$transparency->source_image = 'Water_lilies.png';
// New Image Name (optional)
$transparency->new_image_name = 'water_lilies_transparent';
// Save to folder (optional)
$transparency->save_to_folder = '';
$process = $transparency->make_transparent();
if($process['result'])
{
echo 'The new image ('.$process['new_file_path'].') was saved.';
}
?>
How to show the image in a HTML page?
We can use this class to only generate and output the image without saving it. This way the script can be used to show transparent images ‘on the fly’ from a HTML page. Here’s an example that will give you an idea of how to use it:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> Show Transparent Image </TITLE> <META NAME="Author" CONTENT="Bit Repository"> <META NAME="Keywords" CONTENT="src, image, transparency"> <META NAME="Description" CONTENT="Display a transparent image"> </HEAD> <BODY> <IMG SRC="show_image.php?image=Water_lilies.png&pct=50"> </BODY> </HTML>
The image path from the SRC attribute is: show_image.php?image=Water_lilies.png&pct=60. The script show_image.php will generate the transparent image. To do this it needs the original image, and a transparency value (pct) from 1 to 100. If none is defined, our script will set ‘pct’ to 50 (default). Setting ‘pct’ to 100 won’t add any transparency, but setting it to 40 will make the image 60% transparent.
show_image.php
<?php
error_reporting (E_ALL ^ E_NOTICE);
$pct = $_GET['pct'] ? intval($_GET['pct']) : 50;
$image = $_GET['image'] ? urldecode($_GET['image']) : exit("No Image Requested!");
include 'class.image.transparency.php';
$transparency = new Image_Transparency;
// range of transparency (from 1 to 100)
$transparency->pct = $pct;
// Source Image
$transparency->source_image = $image;
// Make transparent & output image
$process = $transparency->make_transparent();
?>
If you wish to change the transparent white background you can modify the existing parameters for ImageColorAllocateAlpha() from line 81. Currently a white color is obtained if we set Red=255, Green=255 & Blue=255. For example, a red color will have the following RGB values: 255, 0, 0. The last parameter (alpha) can have a value between 0 and 127 (0 - completly opaque, 127 - completly trasparent).
If you have any suggestions and comments regarding this post, consider posting them. If you know some improvements that can be made to this class, please let me know.
The archive is made using WinZip 12.0. If you're having problems unzipping it, consider using WinRar, WinAce or a similar software to extract the files from the archive.Be notified when we have new posts by subscribing to




great thanx
thanks alot ! i was searching for transperacy.