php - Image color value >> 8 & 255 Why should the bit be equal to 255 after shifting?
某草草
某草草 2017-05-16 13:07:44
0
2
569
<?php
/**
imagecolorat — Get the color index value of a pixel

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

Returns the color index value of the pixel at the specified position in the graphic specified by image.

If PHP was compiled with the GD library 2.0 or higher and the image is a truecolor image, this function returns the RGB value of the point as an integer. Use shifting and masking to get the values ​​of the red, green, and blue components:
*/
//echo dechex(255);die;//ff hexadecimal ff = decimal 255
ini_set('display_errors', 'On');

error_reporting(E_ALL | E_STRICT);//E_ALL: all error and warning information except E_STRICT
//E_STRICT: Enables PHP's suggestions for code modifications to ensure the best interoperability and forward compatibility of the code.

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


//Explanation on shift operation https://my.oschina.net/u/435872/blog/134802,



//Shifting n bits to the left means multiplying the data by 2 to the nth power. Shifting n bits to the right means dividing the data by 2 to the nth power and then rounding it.

//print_r(decbin($rgb));//$rgb = 15326445 converted to binary 111010011101110011101101
//echo $rgb >> 16;//233 15326445/2^16 = 233.862991333
//echo decbin($rgb >> 16);//11101001 Shift the binary value of $rgb to the right by 16, and remove the excess part to get
//$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++) {

//Color representation and bit operations 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));

This code

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

What I don’t understand is why the bit and 255 operations are required after the shift

某草草
某草草

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