php-设置图像中每个像素的alpha [英] php - set alpha of each pixel in image

查看:154
本文介绍了php-设置图像中每个像素的alpha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用php gd函数设置图像中每个像素的alpha。

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


推荐答案

Alpha必须定义为0和127。然后您必须使用 imagealphablending() imagesavealpha()来保存和使用Alpha。

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

这篇关于php-设置图像中每个像素的alpha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆