Sunday, June 21, 2009

PHP GD: Getting pixel information

Hello there! It's Sam Yong here again. Earlier on I was developing a PHP script for comparing 2 images and find out their similarity. I was rather successful with it.

Well, today I am going to discuss about PHP's GD library - how to get the Red, Green, Blue information of a pixel of an image resource.

Firstly, when we want to get a pixel's color information from an image, we use imagecolorat. The function returns a 24 bit RGB information in Integer. So by shifting the bits, you will be able to get the individual Red, Green, Blue components of the RGB information in integer.

<?php

// retrieve rgb info from $img resource at ($x,$y)
$rgb = imagecolorat($img,$x,$y);

if($rgb){
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
}

?>


Note that each color has a value that runs from 0 to 255 (8 bit).

No comments: