The average value of the RGB color of the image

I am trying to get the average RGB value of the image color in php.

by gd lib I will 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 this is not good, I think. Processing requires a lot of drums. Is there any other way to do this?

+6
source share
2 answers

I would go with re-fetching:

 $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); 
+5
source

One way to do this is to scale the image to 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; ?> 

This way you do not need to handle messy parts. and you can use more intelligent scaling algorithms to achieve better accuracy.

Edit: you can use Imagick :: resizeImage if you need a more complex algorithm. It can use various algorithms, such as an interpolation filter.

+3
source

Source: https://habr.com/ru/post/894416/


All Articles