3

I was going to rotate an image with transparent color using php gd. However, after the rotation, the transparent color in the image is not transparent any more, and the background is not transparent either. Here is my code.

$im = imagecreatefromgif('/images/80-2.gif');
$rotate = imagerotate($im,30,imagecolorallocatealpha($im, 0, 0, 0, 127));
imagegif($rotate,'/images/rotate.gif');
imagedestroy($im);
imagedestroy($rotate);

Could anybody help me to make it work? Thanks.

CharlesDou
  • 347
  • 1
  • 7
  • 16
  • Seems to be an old problem, here is a work-around: http://www.sitepoint.com/forums/showthread.php?177162-imagerotate-and-alpha-transparency – axel.michel Jan 31 '13 at 18:57
  • Thanks for the reply, but the code is not working for me. I am wondering why I lose all the transparency after the rotation. – CharlesDou Jan 31 '13 at 19:52

2 Answers2

3

to keep transparency in your images you need to use two settings that can be done by calling these functions right after you crete the gd resource

imagealphablending( $im, false );
imagesavealpha( $im, true );
mishu
  • 5,347
  • 1
  • 21
  • 39
  • I don't know why your code doesn't work for me. when I create the original image, I used imagecolortransparent() method to convert red color to transprent color. but after rotation, the transparent color just change back to red.Why that happens? Thanks. – CharlesDou Jan 31 '13 at 19:16
  • so there were more steps than just the ones in this sample; maybe you should try this for both images (I guess you are saving the image as 80-2.gif and processing it again or something like that).. you should see where the transparency is lost.. also I think these calls should be made right after you create the gd resource.. – mishu Jan 31 '13 at 19:19
0

The work-around proposed by alex.michel doesn't work for me with gif: The background is transparent but not the alpha of my original gif. It's blue looking like graphic paper. About mishu's solution, it won't work for gifs (quote from php.net manual):

imagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.

For png I use this, it works great:

    $source = imagecreatefrompng($image);
    imagealphablending($source, false);
    imagesavealpha($source, true);
    $rotated = imagerotate($source, $angle, imageColorAllocateAlpha($source, 0, 0, 0, 127));
    imagealphablending($rotated, false);
    imagesavealpha($rotated, true);
    imagepng($rotated, $image);

I'm still looking for something working for gif...

Maze
  • 21
  • 2