Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background transperancy in imagerotate()

Tags:

php

gd

Since last 2 days, I was trying to add transperancy to the background after rotating an image using imagerotate() PHP-GD function.

But, to my great disappointment, it's not working at all.

It's just giving out a black background behind it.

Here's my code -


$patchImageS    =   'image.png'; // the image to be patched over the final bg
$patchImage =   imagecreatefrompng($patchImageS); // resource of image to be patched
$patchImage     =   imagerotate($patchImage, 23, 0, 0);
imagepng($patchImage,'tt.png');

I tried to change the parameters being passed in function to

imagerotate($patchImage, 23, 5, 0);

imagerotate($patchImage, 23, 0, 5);

Any help would be highly appreciated.

like image 886
kapeels Avatar asked Dec 23 '22 03:12

kapeels


1 Answers

After a number of 99% finished answers, here's the solution I've found:

// Create, or create from image, a PNG canvas
$png = imagecreatetruecolor($width, $height);

// Preserve transparency
imagesavealpha($png , true);
$pngTransparency = imagecolorallocatealpha($png , 0, 0, 0, 127);
imagefill($png , 0, 0, $pngTransparency);

// Rotate the canvas including the required transparent "color"
$png = imagerotate($png, $rotationAmount, $pngTransparency);

// Set your appropriate header
header('Content-Type: image/png');

// Render canvas to the browser
imagepng($png);

// Clean up
imagedestroy($png);

The key here is to include your imagecolorallocatealpha() in your imagerotate() call...

like image 58
z33k3r Avatar answered Jan 08 '23 16:01

z33k3r