使用imagepng()创建的PNG图像如何获取Alpha通道?

10

我尝试获取PNG文件的alpha值,使用的是imagepng()函数。但是问题是alpha只返回了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透明度的代码

$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

我不知道为什么它只返回0而不是1。

2个回答

7

在调用 imagesetpixel 前,您应该先调用 imageAlphaBlendingimageSaveAlpha

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

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>

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