rss
twitter
  •  

PHP-GD: Resize Transparent Image PNG & GIF

| Posted in Programming |

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:

  1. <?
  2. $newImg = imagecreatetruecolor($nWidth, $nHeight);
  3. imagealphablending($newImg, false);
  4. imagesavealpha($newImg,true);
  5. $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
  6. imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
  7. imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
  8. ?>


Full source code for resizing image:

filename: imageresize.php
  1. <?
  2. function resize($img, $w, $h, $newfilename) {
  3.  
  4.  //Check if GD extension is loaded
  5.  if (!extension_loaded('gd') && !extension_loaded('gd2')) {
  6.   trigger_error("GD is not loaded", E_USER_WARNING);
  7.   return false;
  8.  }
  9.  
  10.  //Get Image size info
  11.  $imgInfo = getimagesize($img);
  12.  switch ($imgInfo[2]) {
  13.   case 1: $im = imagecreatefromgif($img); break;
  14.   case 2: $im = imagecreatefromjpeg($img);  break;
  15.   case 3: $im = imagecreatefrompng($img); break;
  16.   default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
  17.  }
  18.  
  19.  //If image dimension is smaller, do not resize
  20.  if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
  21.   $nHeight = $imgInfo[1];
  22.   $nWidth = $imgInfo[0];
  23.  }else{
  24.                 //yeah, resize it, but keep it proportional
  25.   if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
  26.    $nWidth = $w;
  27.    $nHeight = $imgInfo[1]*($w/$imgInfo[0]);
  28.   }else{
  29.    $nWidth = $imgInfo[0]*($h/$imgInfo[1]);
  30.    $nHeight = $h;
  31.   }
  32.  }
  33.  $nWidth = round($nWidth);
  34.  $nHeight = round($nHeight);
  35.  
  36.  $newImg = imagecreatetruecolor($nWidth, $nHeight);
  37.  
  38.  /* Check if this image is PNG or GIF, then set if Transparent*/  
  39.  if(($imgInfo[2] == 1) OR ($imgInfo[2]==3)){
  40.   imagealphablending($newImg, false);
  41.   imagesavealpha($newImg,true);
  42.   $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
  43.   imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
  44.  }
  45.  imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
  46.  
  47.  //Generate the file, and rename it to $newfilename
  48.  switch ($imgInfo[2]) {
  49.   case 1: imagegif($newImg,$newfilename); break;
  50.   case 2: imagejpeg($newImg,$newfilename);  break;
  51.   case 3: imagepng($newImg,$newfilename); break;
  52.   default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
  53.  }
  54.    
  55.    return $newfilename;
  56. }
  57. ?>

Script usage:

filename showimage.php
  1. <?
  2. include_once("resizeimage.php");
  3. $img = "some/dir/image.png"; // File image location
  4. $newfilename = "thumb_image.png"; // New file name for thumb
  5. $w = 100;
  6. $h = 100;
  7.  
  8. $thumbnail = resize($img, $w, $h, $newfilename);
  9.  
  10. echo "<img src='".$thumbnail."'>";
  11. ?>

No, i’m not provide any downloadable source-code.
Just copy-paste this code, and use it well.

VN:F [1.9.13_1145]
Rating: 8.9/10 (38 votes cast)
VN:F [1.9.13_1145]
Rating: +12 (from 12 votes)
PHP-GD: Resize Transparent Image PNG & GIF, 8.9 out of 10 based on 38 ratings

Comments (71)

Awesome code

VA:F [1.9.13_1145]
Rating: 4.0/5 (6 votes cast)
VA:F [1.9.13_1145]
Rating: +2 (from 6 votes)

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.

VA:F [1.9.13_1145]
Rating: 3.5/5 (4 votes cast)
VA:F [1.9.13_1145]
Rating: -3 (from 11 votes)

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.

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 8 votes)

it works for me and others here.
you can show us your source code if you have problem.

thx

VN:F [1.9.13_1145]
Rating: 3.0/5 (4 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 8 votes)

[...] [...]

Thanks so much! Works like a charm. I’ve been trying to get transparencies to work while resizing for some time now.

VA:F [1.9.13_1145]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.13_1145]
Rating: 0 (from 4 votes)

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?

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 4 votes)

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)

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.13_1145]
Rating: +1 (from 3 votes)

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.

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

[...] 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

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: +3 (from 5 votes)

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 ^_^

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

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!!!

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: +1 (from 1 vote)

Thanks. Used here: http://www.rockettheme.com/forum/index.php?f=214&t=130087&p=647850&rb_v=viewtopic#p647850

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Perfect !
Thank you !!

nico

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

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());

VA:F [1.9.13_1145]
Rating: 4.0/5 (4 votes cast)
VA:F [1.9.13_1145]
Rating: +2 (from 2 votes)

You saved my day!

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: +1 (from 1 vote)

Bien vos! thanks

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

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.

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

This example works only with PNG images. Background of my transparent GIF images are still black. can someone help me please?

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Post a comment