Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Alpha from PNG created with imagepng()

Tags:

php

png

I try to get the alpha of a PNG. I'm doing this with imagepng(). My issue is alpha returns only 0.

My code for making PNG with alpha

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

My code for reading 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

I don't know why it returns only 0 and not 1.

like image 314
P. Frank Avatar asked Apr 18 '17 13:04

P. Frank


2 Answers

Frank,

Here is your solution with code

<!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>
like image 139
Arnav Bhowmik Avatar answered Nov 02 '22 09:11

Arnav Bhowmik


You should call imageAlphaBlending and imageSaveAlpha before calling imagesetpixel :

imageAlphaBlending($gd, false);
imageSaveAlpha($gd, true);
imagesetpixel($gd, 0,0, imagecolorallocatealpha($gd, 200,200,200,1));
like image 7
napuzba Avatar answered Nov 02 '22 11:11

napuzba