php - set alpha of each pixel in image

此生再无相见时 提交于 2019-12-08 10:49:11

问题


I want to set the alpha of each pixel in image using php gd functions.

So far i have this:

$src = imagecreatefrompng('image.png');

$w = imagesx($src);
$h = imagesy($src);

$alpha = 204;

for ($x = 0; $x < $w; $x++) {
    for ($y = 0; $y < $h; $y++) {
        // set $alpha for each pixel in $src
    }
}

imagepng($src);
imagedestroy($src);

回答1:


Alpha have to be defined into 0 and 127. Then you have to use imagealphablending() and imagesavealpha() to save and use alpha.

$src = imagecreatefrompng('image.png');

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

$w = imagesx($src);
$h = imagesy($src);

$alpha = round(204/255*127); // convert to [0-127]

for ($x = 0; $x < $w; $x++) {
    for ($y = 0; $y < $h; $y++) {

        // get current color (R, G, B)
        $rgb = imagecolorat($src, $x, $y);
        $r = ($rgb >> 16) & 0xff;
        $g = ($rgb >> 8) & 0xff;
        $b = $rgb & 0xf;

        // create new color
        $col = imagecolorallocatealpha($src, $r, $g, $b, $alpha);

        // set pixel with new color
        imagesetpixel($src, $x, $y, $col);
    }
}
imagepng($src);
imagedestroy($src);


来源:https://stackoverflow.com/questions/49100406/php-set-alpha-of-each-pixel-in-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!