kapeels
kapeels

Reputation: 1702

Background transperancy in imagerotate()

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.

Upvotes: 5

Views: 8586

Answers (3)

Lepy
Lepy

Reputation: 194

For anyone having problems with imagecopyresampled or imagerotate with black bars on background, I have found a code example here:

https://qna.habr.com/q/646622#answer_1417035

        // get image sizes (X,Y)
        $wx = imagesx($imageW);
        $wy = imagesy($imageW);

        // create a new image from the sizes on transparent canvas
        $new = imagecreatetruecolor($wx, $wy);

        $transparent = imagecolorallocatealpha($new, 0, 0, 0, 127);
        $rotate = imagerotate($imageW, 280, $transparent);
        imagealphablending($rotate, true);
        imagesavealpha($rotate, true);

        // get the newest image X and Y
        $ix = imagesx($rotate);
        $iy = imagesy($rotate);

        //copy the image to the canvas
        imagecopyresampled($destImg, $rotate, 940, 2050, 0, 0, $ix, $iy, $ix, $iy);

Upvotes: 0

z33k3r
z33k3r

Reputation: 86

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

Upvotes: 7

oezi
oezi

Reputation: 51807

look for imagesavealpha() in the php-documentation - i think this is what you are looking for.

EDIT: here's an example:

$png = imagecreatefrompng('./alphachannel_example.png');

// Do required operations
$png = imagerotate($png, 23, 0, 0);

// Turn off alpha blending and set alpha flag
imagealphablending($png, false);
imagesavealpha($png, true);

// Output image to browser
header('Content-Type: image/png');

imagepng($png);
imagedestroy($png);

Upvotes: 5

Related Questions