php - 图片颜色值 >> 8 & 255 移位后为什么要 位与255
某草草
某草草 2017-05-16 13:07:44
0
2
520
<?php
/**
imagecolorat — 取得某像素的颜色索引值

int imagecolorat ( resource $image , int $x , int $y )

返回 image 所指定的图形中指定位置像素的颜色索引值。

如果 PHP 编译时加上了 GD 库 2.0 或更高的版本并且图像是真彩色图像,则本函数以整数返回该点的 RGB 值。用移位加掩码来取得红,绿,蓝各自成分的值: 
*/
//echo dechex(255);die;//ff  16进制ff = 10进制255  
ini_set('display_errors', 'On');

error_reporting(E_ALL | E_STRICT);//E_ALL:除E_STRICT外所有错误和警告信息
//E_STRICT:启用 PHP 对代码的修改建议,以确保代码具有最佳的互操作性和向前兼容性。

$im = ImageCreateFromPng("images/4.png");
//$rgb = ImageColorAt($im, 100, 100);


//关于移位运算的讲解  https://my.oschina.net/u/435872/blog/134802,



//向左移n位表示将数据乘以2的n次方,向右移n位表示将数据除以2的n次方后取整

//print_r(decbin($rgb));//$rgb = 15326445 转为二进制  111010011101110011101101
//echo $rgb >> 16;//233   15326445/2^16 = 233.862991333
//echo decbin($rgb >> 16);//11101001  将$rgb的二进制值向右移位16,超出部分去掉得到
//$r = ($rgb >> 16) & 0xFF;
//$g = ($rgb >> 8) & 0xFF;
//$b = $rgb & 0xFF;



function average($img) {
    $w = imagesx($img);
    $h = imagesy($img);
    $r = $g = $b = 0;
    for($y = 0; $y < $h; $y++) {
        for($x = 0; $x < $w; $x++) {

//颜色表示和位操作  http://www.cnblogs.com/mengdd/p/3254292.html
            $rgb = imagecolorat($img, $x, $y);
            $r += $rgb >> 16;
            $g += $rgb >> 8 & 255;
            $b += $rgb & 255;
        }
    }
    $pxls = $w * $h;
    $r = dechex(round($r / $pxls));
    $g = dechex(round($g / $pxls));
    $b = dechex(round($b / $pxls));
    if(strlen($r) < 2) {
        $r = 0 . $r;
    }
    if(strlen($g) < 2) {
        $g = 0 . $g;
    }
    if(strlen($b) < 2) {
        $b = 0 . $b;
    }
    return "#" . $r . $g . $b;
}


print_r(average($im));

这段代码

$r += $rgb >> 16;
$g += $rgb >> 8 & 255;
$b += $rgb & 255;
          

不明白的地方是为什么移位后还要位与255操作

某草草
某草草

reply all(2)
伊谢尔伦

(mask & 0xff) 目的在于消除maskEnter high-order data of more than 8 digits to ensure that the result is within the range of 0-255

阿神

If $rgb is 0x111111 你又不 & 255,结果会是 $g = 0x1111 $b=0x111111

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!