Put your message here! Contact me for more information
 
 








 


I’ve just made a comments on php.net’s manual page under imagecopyresized() about resizing transparent PNGs with GD. Here is the post again, hopefully it can help someone. Comments are welcome.

Belows is the code snipet that allows you to resize a transparent PNG and composite it into another image. The code is tested to work with PHP5.1.2, GD2, but I think it can also work with other versions of PHP and GD.

The code has been commented to help you read through it. The idea of resizing the transparent PNG image is to create a new destination image which is completely transparent then turn off the imageAlphaBlending of this new image so that when the PNG source file is copied, its alpha channel is still retained.

===Code:===


/**
* Compose a PNG file over a src file.
* If new width/ height are defined, then resize the PNG (and keep all the transparency info)
* Author: Alex Le - http://www.alexle.net
*/
function imageComposeAlpha( &$src, &$ovr, $ovr_x, $ovr_y, $ovr_w = false, $ovr_h = false)
{
if( $ovr_w && $ovr_h )
$ovr = imageResizeAlpha( $ovr, $ovr_w, $ovr_h );

/* Noew compose the 2 images */
imagecopy($src, $ovr, $ovr_x, $ovr_y, 0, 0, imagesx($ovr), imagesy($ovr) );
}

/**
* Resize a PNG file with transparency to given dimensions
* and still retain the alpha channel information
* Author: Alex Le - http://www.alexle.net
*/
function imageResizeAlpha(&$src, $w, $h)
{
/* create a new image with the new width and height */
$temp = imagecreatetruecolor($w, $h);

/* making the new image transparent */
$background = imagecolorallocate($temp, 0, 0, 0);
ImageColorTransparent($temp, $background); // make the new temp image all transparent
imagealphablending($temp, false); // turn off the alpha blending to keep the alpha channel

/* Resize the PNG file */
/* use imagecopyresized to gain some performance but loose some quality */
imagecopyresized($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
/* use imagecopyresampled if you concern more about the quality */
//imagecopyresampled($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
return $temp;
}
?>

===Example usage:===


header('Content-type: image/png');

/* Open the photo and the overlay image */
$photoImage = ImageCreateFromJPEG('images/MiuMiu.jpg');
$overlay = ImageCreateFromPNG('images/hair-trans.png');

$percent = 0.8;
$newW = ceil(imagesx($overlay) * $percent);
$newH = ceil(imagesy($overlay) * $percent);

/* Compose the overlay photo over the target image */
imageComposeAlpha( $photoImage, $overlay, 86, 15, $newW, $newH );

/* Open another PNG file, then resize and compose it */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 10, 20, imagesx($watermark)/2, imagesy($watermark)/2 );

/**
* Open the same PNG file then compose without resizing
* As the original $watermark is passed by reference, it was resized already.
* So we have to reopen it.
*/
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 80, 350);
Imagepng($photoImage); // output to browser

ImageDestroy($photoImage);
ImageDestroy($overlay);
ImageDestroy($watermark);
?>


 

38 Responses to “Resize and Compose Transparent PNG with PHP



9:19 am
October 19, 2006
#1247

Thanks… that helped a lot. The transparency has been causing me grief. I was just about to switch to system(’composite …’);




10:15 am
October 20, 2006
#1294

@three
You are very welcome. The PHP documentations on PNG transparency is very shallow I have to say. I’m glad that my code snippet save you some time :)

Alex




12:01 pm
November 30, 2006
#2812

thanks!




12:54 pm
December 11, 2006
#4399

Hi. This script works great.
However, when i modify this script slightly, it crashes the server. Im just trying to Output the final Png Overlayed on JPG (no need for the watermark), as a JPG file.
Any help would be great!




1:57 pm
December 11, 2006
#4422

@James,

I’m not sure when you wrote “it crashes the server”, do you mean your server actually crashed, or just the script was just giving errors”?

If it’s possible, you can just forward me the code and I’ll take a look into it.

Best,

Alex




2:56 pm
December 11, 2006
#4436

Hey.
I apologize for wasting your blog space here.. turns out it was all due to Operator Error. (the actual server crashed yes. i used an absolute percentage by mistake; heh, so you can imagine how much work apache was trying to execute).




5:07 pm
December 11, 2006
#4459

@James,

Not a problem buddy! I was thinking about how the script could possible crash the server (that’s pretty scary isn’t it?) But well, if you put in 80% then it’s 80 times bigger than the original image. Phew, that’s a lot of RAM to be chewed awa. No wonder why apache is going wild… Good catch though.




12:46 pm
December 17, 2006
#7692

thx - this is exactly what I needed to allow my clients to overlay png on video and customize/rebrand our player.

-nathan




Haoshiro
8:07 pm
February 9, 2007
#16124

This worked for me after one addition, add this after the call to imagealphablending():

imagesavealpha ( $temp, true ); // Save full alpha

One other minor note, I think “Compose” should actually be “Composite” for the sake of clarity :)




7:31 pm
March 22, 2007
#19606

Yes! This is bitchen!

To All & Haoshiro - I kept getting a white or black bg depending on the true/false attribute for imagealphablending(). I added the imagesavealpha() code like you mentioned, and now I have transparent backgrounds! SWEET!

btw, Im testing on Apache 2 PHP 4.4.




10:58 am
April 26, 2007
#25266

Alex, you are the best programmer, you are the magician!!!
THANK YOU!




Bur
5:32 am
May 20, 2007
#30825

Big thanks for script, its work, but
imagesavealpha ( $temp, true );
nedeed with use only resize trasparent png.




Steve
8:20 am
May 31, 2007
#33415

Thanks. Your script was very close. Adding the imagesavealpha AND using imagecopyresampled got me the rest of the way. Images are spot on now, and I don’t have to worry about creating 25 thousand half sized images.




11:45 am
June 1, 2007
#34109

Script works great I just have a problem resizing when the original image contains black parts. Those parts will turn transparent although it is not intended.




4:14 am
June 30, 2007
#41799

Hi, can I have the images or a live demo. I am also struggling to create a watermark to a transparent png image. It would be nice if you provide a demo link.




Penguinboy
7:08 am
July 15, 2007
#44382

i had the same problem as zoltan, but adding the following made the images perfect, retaining black:

imagesavealpha ($temp, true);
imageAntiAlias($temp,true);

the antialias makes the images look way better (but it’s slower), i dont know if anything else does, but the antialias requires the GD library.




2:53 pm
September 3, 2007
#54111

Alex, very good job! I was slightly bugging out when overlaying PNGs using imagecopymerged and seeing very strange image artifacts. After looking at your code snippet, I gave imagecopy a try. And voila, everything worked. I am currently working on an fb app that will be leveraging the gd library heavily to produce custom user images on the fly. If you have any ideas about optimization, let me know. My current approach will be to store the image after it’s generated, this way it does not need to be generated on a per-user, per page load basis. That would probably eat at the memory really quickly for a user base over a hundred thousand (which is what we will likely be working with , since it’s on facebook).




Jay
11:37 am
September 16, 2007
#57613

Thanks for the script alex. this was annoying me for hours. i had the images overlaying fine without the alpha though. again, many thanks, your work is much appreciated

Regards
Jay




5:39 pm
October 13, 2007
#65654

Thanks a lot. You are the only person on the web that helped me with this issue.




Chi
3:30 am
October 29, 2007
#72823

thank you, thank you VERY much!




kaqkk
1:22 am
October 30, 2007
#73340

Thank you!

I’ve spent lot of time to investigate this transparency issue. This is the first script that really working.

Best regards,
kaqkk




Stiffler
7:48 am
December 7, 2007
#85657

hey dude!

great job! it works perfect… it’s exactly the things i was looking for :)




Nico
3:34 am
January 10, 2008
#99135

Thank you very much, worked out perfect for me :-)




dilbar
1:25 pm
January 25, 2008
#106389

Must Say Thank You, you really save my time




Paul
5:25 am
February 22, 2008
#120353

Many thanks, That code ironed out the problems for me.




Mikael
2:18 pm
February 24, 2008
#121329

Why do I get this errormessage:

Warning: imagesx(): supplied argument is not a valid Image resource in D:\customers\*****************\inc.uploadpng.php on line 33

This is how i use the funtion:
imageResizeAlpha(’image.png’, 100, 100);




2:57 pm
April 8, 2008
#140338

hi!
really a great great thank you for publishing this script - helped me out of spending hours and hours of programming!
best wishes from austria,
philip




2:05 pm
May 6, 2008
#151937

GREAT JOB!

many many thanks from Italy :D




Rzuber
2:19 pm
July 8, 2008
#180764

AWESOME!

Thanks from Poland :)




9:35 am
August 13, 2008
#197759

Thank you from France.
You help me a lot with this piece of code.

Thank you very much.




JI Zhang
5:07 am
September 15, 2008
#210833

It seems nice work. but my question is

Can php GD do the job like some web based Java UML editor?

can any body tell me?

Thanks




BlueClock
12:32 pm
December 9, 2008
#235798

imagecopyresampled does not retain alpha channels in my case, when resizing and optimizing images.

Had to use imagecopyresized.
and imagesavealpha() of course.

imageAntiAlias had virtually no effect in my case (probably because I’m making 320×200 thumbs).




Merci !
6:20 pm
February 20, 2009
#247919

Merci beaucoup !, ça ma vraiment bien débloqué !!!
Thx ! it’s help me so much !!




11:39 pm
February 25, 2009
#248671

Following is a similar example for watermarking uploaded images using GIF image:

http://911-need-code-help.blogspot.com/2008/11/watermark-your-images-with-another.html




3:34 pm
March 25, 2009
#253098

Thanks! Awesome work - used part of the code to round the edges of user uploaded images in CMS.




8:54 am
May 13, 2009
#263157

Many thanks from Italy.
Your piece of code works like a charm, I crashed my head for hours in the attempt to understand how to resize images in PHP by keeping the transparency for PNG images and GIF images.




6:30 pm
August 9, 2009
#273238

Thank you so much. This fixed my bizzare problem.

To anyone who uses this and still has problems, break your code down into something simple. I thought even this didn’t work, but it did with a process of elimination.




Pablo
9:17 am
November 9, 2009
#278333

Thanks a lot! This worked smoothly for me :-)




 

Leave a Reply