phpimagegddynamic-image-generation

imagerotate with alpha color not work


I have a strange situation.

it looks like background not always transparent, but on some degree it broken...

good one 30 degree

not good

here is the code:

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

just can`t understand what is going on... am i missed somth?

EDIT1

added that func:

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

but now stuck withthat square do not want to be transparent....

almost


Solution

  • The imagerotate is poorly implemented; I notice rounding off errors/cut edges often. If you must, you can use a 24bit transparent PNG image instead of transparent GIF (PNG supports alpha transparency which means the edges will be blended nicely with HTML background color).

    The function has transparency issues and the workaround is to add two extra lines:

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

    Result:

    result 0 to 359 degree

    As an alternate, may I suggest CSS transform?

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