使用alpha颜色的imagerotate无法工作

4

我有一个奇怪的情况。

看起来背景不总是透明的,但在某种程度上它被破坏了...

好的 30 度

不好的

这是代码:

$angle = !empty($_GET['a']) ? (int)$_GET['a'] : 0;

$im = imagecreatefromgif(__DIR__ . '/track/direction1.gif');
imagealphablending($im, false);
imagesavealpha($im, true);

$transparency = imagecolorallocatealpha($im, 0, 0, 0, 127);
$rotated = imagerotate($im, $angle, $transparency);

imagealphablending($rotated, false);
imagesavealpha($rotated, true);

imagepng($rotated);
imagedestroy($rotated);

imagedestroy($im);
header('Content-Type: image/png');

我完全不理解发生了什么... 是我错过了什么吗?

编辑1

添加了那个函数:

if(!function_exists('imagepalettetotruecolor'))
{
    function imagepalettetotruecolor(&$src)
    {
        if(imageistruecolor($src))
        {
            return true;
        }

        $dst = imagecreatetruecolor(imagesx($src), imagesy($src));
        $black = imagecolorallocate($dst, 0, 0, 0);
        imagecolortransparent($dst, $black);

        $black = imagecolorallocate($src, 0, 0, 0);
        imagecolortransparent($src, $black);

        imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
        imagedestroy($src);

        $src = $dst;

        return true;
    }
}

但是现在卡在这个正方形,不想透明…

almost

2个回答

4

imagerotate 函数的实现不够完善,我经常遇到四舍五入错误/边缘被削减的问题。如果必须使用透明GIF,可以使用24位透明PNG图像代替(PNG支持Alpha透明度,这意味着边缘将与HTML背景颜色混合得很好)。

该函数存在透明度问题,解决方法是添加两行额外的代码:

<?php
$angle = (int) $_GET['a'];
$source = imagecreatefrompng(__DIR__ . DIRECTORY_SEPARATOR . 'direction1.png');
$rotation = imagerotate($source, $angle, imageColorAllocateAlpha($source, 0, 0, 0, 127));
imagealphablending($rotation, false); // handle issue when rotating certain angles
imagesavealpha($rotation, true);      // handle issue when rotating certain angles
header('Content-type: image/png');
imagepng($rotation);
imagedestroy($source);
imagedestroy($rotation);

结果:

0到359度的结果

作为替代,我可以建议使用CSS变换

img:nth-child(2) {
  transform: rotate(45deg);
}
img:nth-child(3) {
  transform: rotate(90deg);
}
img:nth-child(4) {
  transform: rotate(135deg);
}
<img src="http://i.stack.imgur.com/oZlZ9.png">
<img src="http://i.stack.imgur.com/oZlZ9.png">
<img src="http://i.stack.imgur.com/oZlZ9.png">
<img src="http://i.stack.imgur.com/oZlZ9.png">


1

imagecreatefromgif()创建的是一个调色板图像而不是真彩色图像(因为这是GIF格式编码图像的方式)。在有调色板的图像上,透明度与真彩色图像上的透明度工作方式不同,而您计算出的$transparency值并没有帮助。

解决方法是在旋转之前将$im转换为真彩色。函数imagepalettetotruecolor()就是做这个的。它自PHP 5.5版本以来就可用。如果您卡在旧版本上,则需要自己实现。检查文档页面上的最后一个示例,它已经实现了并且还处理了透明度(运行时会遇到一些小错误)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接