Skip to main content

PHP: dominant colour of image

12th October, 2022

Updated: 13th October, 2022

    $i = imagecreatefromjpeg("image.jpg");
    
    for ($x=0;$x<imagesx($i);$x++) {
        for ($y=0;$y<imagesy($i);$y++) {
            $rgb = imagecolorat($i,$x,$y);
            $r   = ($rgb >> 16) & 0xFF;
            $g   = ($rgb >>  & 0xFF;
            $b   = $rgb & 0xFF;
    
            $rTotal += $r;
            $gTotal += $g;
            $bTotal += $b;
            $total++;
        }
    }
    
    $rAverage = round($rTotal/$total);
    $gAverage = round($gTotal/$total);
    $bAverage = round($bTotal/$total);

    c31e6692-5b5a-4f15-8343-ba64759ef8ef

    Created on: 12th October, 2022

    Last updated: 13th October, 2022

    Tagged With: