从使用 imagepng() 创建的 PNG 中获取 Alpha

Get Alpha from PNG created with imagepng()

我尝试获取 PNGalpha。我正在使用 imagepng() 进行此操作。 我的问题是 alpha returns 只有 0.

我用 alpha 制作 PNG 的代码

$x = 1;
$y = 1;
$gd = imagecreatetruecolor($x, $y); 
imagesetpixel($gd, 0,0, imagecolorallocatealpha($gd, 200,200,200,1));
imageAlphaBlending($gd, false);
imageSaveAlpha($gd, true);
imagepng($gd,"test.png");
imagedestroy($gd);

我读取PNG alpha的代码

$im = imagecreatefrompng("test.png");
$rgb = imagecolorat($im, 0, 0);
$colors = imagecolorsforindex($im, $rgb);
$red = (int) $colors["red"]; 
$blue = (int) $colors["blue"];
$green = (int) $colors["green"]; 
$alpha = (int) $colors["alpha"]; // return only 0

我不知道为什么 returns 只有 0 而不是 1。

你应该在调用 imagesetpixel 之前调用 imageAlphaBlendingimageSaveAlpha :

imageAlphaBlending($gd, false);
imageSaveAlpha($gd, true);
imagesetpixel($gd, 0,0, imagecolorallocatealpha($gd, 200,200,200,1));

弗兰克,

这是您的解决方案代码

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Test</title>

    </head>
    <body>

        <a href="index.php" class="navbar-brand">
            <?php
            $x = 1;
            $y = 1;
            $gd = imagecreatetruecolor($x, $y);
            imageAlphaBlending($gd, false);
            imageSaveAlpha($gd, true);
            imagesetpixel($gd, 0, 0, imagecolorallocatealpha($gd, 200, 200, 200, 1));
            imagepng($gd, 'img/logo.png" ');
            imagedestroy($gd);

            $im = imagecreatefrompng('img/logo.png');
            $rgb = imagecolorat($im, 0, 0);
            $colors = imagecolorsforindex($im, $rgb);
            $red = (int) $colors["red"];
            $blue = (int) $colors["blue"];
            $green = (int) $colors["green"];
            echo $alpha = (int) $colors["alpha"]; // return only 0
            ?>
        </a>

    </body>
</html>