상현에 하루하루
개발자의 하루

PHP로 이미지를 기준으로 텍스트 색상 정하기

( 업데이트: )

웹사이트의 디자인에서 light 테마는 검은색 텍스트를 dark 테마는 흰색 텍스트를 정하고 텍스트 스타일을 정한다. 어느정도 규칙이 정해져있고 해당하는 규칙에 따라 텍스트 색상을 정한다면 코드로 가능하다.

이미지를 가져와 분석해서 어떤 텍스트 색상이다 정해주면 작성자가 하나하나 검토해서 직접 색상을 지정하지 않아도 된다.

/**
 * 이미지 파일의 평균 휘도를 구한다.
 * 
 * @param mixed $filename 
 * @param int $num_samples 
 * @return void|bool 
 */
function get_avg_luminace($filename, $num_samples = 10)
{
    // 파일의 확장자를 기준
    if (strpos($filename, 'png')) {
        $img = imagecreatefrompng($filename);
    } elseif (strpos($filename, 'jpg')) {
        $img = imagecreatefromjpeg($filename);
    } else return;

    $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;

            // 참고한 간단한 휘도 공식
            // http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
            $lum = ($r + $r + $b + $g + $g + $g) / 6;

            $total_lum += $lum;

            $sample_no++;
        }
    }

    // 평균 구하기
    $avg_lum = $total_lum / $sample_no;

    // true -> black text , false -> white text
    return $avg_lum > 170;
}Code language: PHP (php)

참고