Background image dark or light?

删除回忆录丶 提交于 2019-11-30 02:26:55

I thought this was quite an interesting problem to solve, so i hacked up a quick script to do it. following the other suggestions provided

<?php

    // TODO supply your own filenames
    $filenames = array(
        'testpics/client-bella-vi.jpg',
        'testpics/istockphoto_8577991-concept-of-business-people-crowd.jpg',
        'testpics/medium-gray.jpg');

    // loop though each file
    foreach ($filenames as $filename) {

        echo "$filename<br/>";

        $luminance = get_avg_luminance($filename,10);
        echo "AVG LUMINANCE: $luminance<br />";

        // assume a medium gray is the threshold, #acacac or RGB(172, 172, 172)
        // this equates to a luminance of 170
        if ($luminance > 170) {
            echo "Black Text<br />";
        } else {
            echo 'White Text<br />';
        }

        echo "<br />";
    }
    exit;

    // get average luminance, by sampling $num_samples times in both x,y directions
    function get_avg_luminance($filename, $num_samples=10) {
        $img = imagecreatefromjpeg($filename);

        $width = imagesx($img);
        $height = imagesy($img);

        $x_step = intval($width/$num_samples);
        $y_step = intval($height/$num_samples);

        $total_lum = 0;

        $sample_no = 1;

        for ($x=0; $x<$width; $x+=$x_step) {
            for ($y=0; $y<$height; $y+=$y_step) {

                $rgb = imagecolorat($img, $x, $y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                // choose a simple luminance formula from here
                // http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
                $lum = ($r+$r+$b+$g+$g+$g)/6;

                $total_lum += $lum;

                // debugging code
     //           echo "$sample_no - XY: $x,$y = $r, $g, $b = $lum<br />";
                $sample_no++;
            }
        }

        // work out the average
        $avg_lum  = $total_lum/$sample_no;

        return $avg_lum;
    }

you could possibly use some image processing algorithm that would examine the pixel brightness and calculate mean image brightness.

this document will get you started:

http://www.kweii.com/site/color_theory/2007_LV/BrightnessCalculation.pdf

nategood

If you're looking to use GD, trying using imagecolorat to sample pixels of the image. You can determine the RGB of the color as shown on the PHP man page.

Next, take the RGB sample(s) and determine their brightness using a basic luminance formula.

Determine a threshold for what you consider light vs. dark and categorize accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!