I'm trying to get average of RGB color of Image in php.
by gd lib I program it
$x = imagesx($im);
$y = imagesy($im);
for ($i = 0;$i < $x;$i++)
for ($j = 0;$j < $y;$j++){
$rgb = imagecolorat($im,$i,$j);
$sum['R'] += ($rgb >> 16) & 0xFF;
$sum['G'] += ($rgb >> 8) & 0xFF;
$sum['B'] += $rgb & 0xFF;
}
But it's not good way I think. It needs a lot of ram to process. Is there another way to do it?
The average colour is the sum of all pixels divided by the number of pixels. However, this approach may yield a colour different to the most prominent visual color. What you might really want is dominant color rather than average colour.
The three RGB colors are each 8-bits (possible values [0.. 255], 28 = 256) of each of Red, Green, and Blue. The three 8-bit RGB components can create up to 256×256×256 = 16.7 million possible RGB color combinations, called 24-bit "color". Of course, any one real photo image will not use most of these possible colors.
The team determined that the average color of the universe is a beige shade not too far off from white.
Click on the color selector icon (the eyedropper), and then click on the color of in- terest to select it, then click on 'edit color'. 3. The RGB values for that color will appear in a dialogue box.
I would go with resampling:
$tmp_img = ImageCreateTrueColor(1,1);
ImageCopyResampled($tmp_img,$im,0,0,0,0,1,1,$x,$y); // or ImageCopyResized
$rgb = ImageColorAt($tmp_img,0,0);
One way to do this is to scale the picture to just one pixel and then use the colors of that pixel as a reference.
<?php
$image = new Imagick('800x480.jpg');
$image->scaleImage(1, 1, true);
$pixel = $image->getImagePixelColor(0,0);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
?>
That way you don't need to handle messy details. and you can use smarter scaling algorithms to achieve better precision.
Edit: You can use Imagick::resizeImage instead if you need a more sophisticated algorithm. it can use different algorithms like Interpolation filter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With