开发者

average of RGB color of Image

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)开发者_StackOverflow & 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜