Background transperancy in imagerotate()

冷暖自知 提交于 2019-12-01 20:54:12

问题


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.


回答1:


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




回答2:


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);


来源:https://stackoverflow.com/questions/2693585/background-transperancy-in-imagerotate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!