Steffan Donal
Steffan Donal

Reputation: 2334

How to rotate an image in GD Image Library while keeping transparency?

I'm making a skin previewer for my site; I need to rotate parts of an image to create a representation of this for my users to see.

The skin is a PNG file, and all parts of it may have transparency or even none at all.

I need to be able to rotate this image while keeping any transparency inside the image transparent, while also having the extended borders (You know, the area that wasn't part of the image before it was rotated) transparent.

All of my attempts have left a black border around the image itself.

Any help?

Upvotes: 1

Views: 1459

Answers (4)

SwingingTom
SwingingTom

Reputation: 65

when using imagerotate() the third parameter is for background.
So we can simply feed a transparent color.

$gd_canvas = imagecreatetruecolor(800, 600);
imagesavealpha($gd_canvas, true);

// Allocate a color for transparency
$transparent = imagecolorallocatealpha($gd_canvas , 0, 0, 0, 127);
imagefill($gd_canvas, 0, 0, $transparent);



// Load the image to be rotated
$img = imagecreatefrompng('my-bitmap.png');
$rotated = imagerotate($img, 15, $transparent);

imagecopy($gd_canvas, $rotated , 0, 0, 0, 0, imagesx($rotatedSceau), imagesy($rotatedSceau));

Answer found from https://www.developpez.net/forums/d1309593/php/bibliotheques-frameworks/gd-imagerotate-transparence/

Upvotes: 0

Peter
Peter

Reputation: 1348

I use that to rotate a PNG and preserve transparency color. Works like a charm. It's "basic GD".

 $rotation = 135;
 $handle_rotated = imagerotate($handle_not_rotated,$rotation,0);
 imagealphablending($handle_rotated, true);
 imagesavealpha($handle_rotated, true); 

Don't know if it's what you're looking for?

Upvotes: 1

Mike C
Mike C

Reputation: 1778

  1. Cut out the piece of the image you want to rotate
  2. Rotate preserving alpha using something like this http://www.exorithm.com/algorithm/view/rotate_image_alpha
  3. Merge back in preserving alpha using the following:

-

imagesetbrush($destimg, $srcimg);
// x, y are the center of target paste location
imageline($destimg, $x, $y, $x, $y, IMG_COLOR_BRUSHED);

Upvotes: 2

volvox
volvox

Reputation: 3060

You may want to check here for some uses for libpng (which will need zlib). If you are on linux you can write something in perl. CPAN GD module might be your ticket.

Upvotes: 0

Related Questions