PHP-GD: Resize Transparent Image PNG & GIF
| Posted in Programming | Posted on 10-07-2008
71
By default, you will get black background if you resize a transparent image. To fix it, you need set alpha channel imagecolorallocatealpha to 127.
With imagecolorallocatealpha, it will allocate a color for an image.
Usage:
int imagecolorallocatealpha ( resource image, int red, int green, int blue, int alpha)
From PHP manual:
imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha which may have a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.
Returns FALSE if the allocation failed.
Before using it, you must set to false the blending mode for an image and set true the flag to save full alpha channel information.
Example:
-
<?
-
$newImg = imagecreatetruecolor($nWidth, $nHeight);
-
imagealphablending($newImg, false);
-
imagesavealpha($newImg,true);
-
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
-
imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
-
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
-
?>
Full source code for resizing image:
-
<?
-
function resize($img, $w, $h, $newfilename) {
-
-
//Check if GD extension is loaded
-
if (!extension_loaded('gd') && !extension_loaded('gd2')) {
-
trigger_error("GD is not loaded", E_USER_WARNING);
-
return false;
-
}
-
-
//Get Image size info
-
$imgInfo = getimagesize($img);
-
switch ($imgInfo[2]) {
-
case 1: $im = imagecreatefromgif($img); break;
-
case 2: $im = imagecreatefromjpeg($img); break;
-
case 3: $im = imagecreatefrompng($img); break;
-
default: trigger_error('Unsupported filetype!', E_USER_WARNING); break;
-
}
-
-
//If image dimension is smaller, do not resize
-
if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
-
$nHeight = $imgInfo[1];
-
$nWidth = $imgInfo[0];
-
}else{
-
//yeah, resize it, but keep it proportional
-
if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
-
$nWidth = $w;
-
$nHeight = $imgInfo[1]*($w/$imgInfo[0]);
-
}else{
-
$nWidth = $imgInfo[0]*($h/$imgInfo[1]);
-
$nHeight = $h;
-
}
-
}
-
$nWidth = round($nWidth);
-
$nHeight = round($nHeight);
-
-
$newImg = imagecreatetruecolor($nWidth, $nHeight);
-
-
/* Check if this image is PNG or GIF, then set if Transparent*/
-
if(($imgInfo[2] == 1) OR ($imgInfo[2]==3)){
-
imagealphablending($newImg, false);
-
imagesavealpha($newImg,true);
-
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
-
imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
-
}
-
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
-
-
//Generate the file, and rename it to $newfilename
-
switch ($imgInfo[2]) {
-
case 1: imagegif($newImg,$newfilename); break;
-
case 2: imagejpeg($newImg,$newfilename); break;
-
case 3: imagepng($newImg,$newfilename); break;
-
default: trigger_error('Failed resize image!', E_USER_WARNING); break;
-
}
-
-
return $newfilename;
-
}
-
?>
Script usage:
-
<?
-
include_once("resizeimage.php");
-
$img = "some/dir/image.png"; // File image location
-
$newfilename = "thumb_image.png"; // New file name for thumb
-
$w = 100;
-
$h = 100;
-
-
$thumbnail = resize($img, $w, $h, $newfilename);
-
-
echo "<img src='".$thumbnail."'>";
-
?>
No, i’m not provide any downloadable source-code.
Just copy-paste this code, and use it well.
–





Awesome code
I’ve been trying to use to maintain transparency with GIFs and PNGs. It does not seem to work for either GIF or PNG however, sorry to say.
I’ve been trying to use this code to maintain transparency with GIFs and PNGs.
It does not seem to work for either GIF or PNG however, I am sorry to report.
it works for me and others here.
you can show us your source code if you have problem.
thx
[...] [...]
Thanks so much! Works like a charm. I’ve been trying to get transparencies to work while resizing for some time now.
I tried this with no luck as well. I could not use imagecopyresampled, and had to use the following instead:
imagecolortransparent($newImg, $transparent);
imagecopyresized($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
This works for the transparency, but the image quality is poor (resize is worse than resample). Any ideas why I can’t use resample?
Thanks! that fixed it.
while trying to find the problem i noticed the actual image was transparent, the php created image was transparent then i resized imagecopyresampled() to be smaller than my full image and it is that function that is losing the transparency of the copied image:
[php]
$bgImageURL = ‘blue-bg.gif’;
$bgImage = imagecreatetruecolor(156,40);
imagealphablending($bgImage, false);//needed
//imagesavealpha($bgImage,true); //not needed
$transparent = imagecolorallocatealpha($bgImage, 255, 255, 255,127);//needed
//imagecolortransparent($bgImage,$transparent); //not needed
imagefilledrectangle($bgImage, 0, 0, 156, 40, $transparent);//needed
$srcimage = @imagecreatefromgif($bgImageURL);
imagecopyresized($bgImage, $srcimage, 0, 0, 0, 0, 146, 30, 1000, 250);
//imagecopyresampled($bgImage,$srcimage,0,0,0,0, 146,30,1000,250);//loses transparency
header(‘content-type: image/gif’);
imagegif($bgImage);
[/php]
likely sounds like a bug in later versions
i am running PHP Version 5.2.6 & GD Version: bundled (2.0.34 compatible)
Thank you Miaz,
I am creating an image resize feature for WordPress and I had ssiues with PNG’s always having a balck background when resized.
I use a part of you code and resized PNG images now appear as they should. I have not yet tested it for GIF’s but I’m sure your code will work as it works for PNG’s.
You can take a look a look at a WordPress post that has a transparent PNG here:
http://www.karavadra.net/wordpress/contact-form-for-wordpress
and if you finf this post in the arhcives or search results then you will see a resized transparent version.
Thank you again.
[...] You can extract and resize JPEG, GIF and PNG images from your posts. (PNG and GIF transparency is in development. PNG transparency on resize is working thanks to soem code by Miaz Mauzka). [...]
Not working for transparent GIF’s – PHP 5 / GD 2 / Linux
Hello, nice script thanks for sharing, just a small error in the usage script
$image = “some/dir/image.png”; // File image location
should be
$img = “some/dir/image.png”; // File image location
i need it to keep the same ratio as the original image, i’ll try to modify it later, but any suggestion is welcome ^_^
Excelent!! I found some errors in the script (resizeimage.php is imageresize.php)
The only code working on the network!
—
Excelente!! Encontre un par de errores en el script (resizeimage.php se llama imageresize.php)
El unico codigo que funciona en la red!!
Saludos!!!
Thanks. Used here: http://www.rockettheme.com/forum/index.php?f=214&t=130087&p=647850&rb_v=viewtopic#p647850
Perfect !
Thank you !!
nico
I don’t know if all problems are solved, but here are my changes based on the initial script, to make everything (PNG, GIF) work well:
$new_image = imagecreatetruecolor($width, $height);
// Preserve transparency
$transparent_index = imagecolortransparent($this->image);
if ($transparent_index >= 0) { // GIF
imagepalettecopy($this->image, $new_image);
imagefill($new_image, 0, 0, $transparent_index);
imagecolortransparent($new_image, $transparent_index);
imagetruecolortopalette($new_image, true, 256);
}
else // PNG
{
imagealphablending($new_image, false);
imagesavealpha($new_image,true);
$transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
imagefilledrectangle($new_image, 0, 0, $width,$height, $transparent);
}
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
[...] http://www.akemapa.com/2008/07/10/php-gd-resize-transparent-image-png-gif/ [...]
You saved my day!
Bien vos! thanks
Oh man! I’ve been trying to find a fix for this for months and months for our WordPress blog.
The fix offered at the top didn’t do it, Benjamin’s fix did the trick. I think the problem is that GIF and PNG8 have different pallette numbers for the transparent, which wasn’t being considered by earlier fixes?
Sooo pleased to see this problem dealt with once and for all.
This example works only with PNG images. Background of my transparent GIF images are still black. can someone help me please?