LoginSignup
13
6

More than 3 years have passed since last update.

色コードの明暗を判定する

Last updated at Posted at 2016-11-18

課題

例えば、「#4631b9」のような色のコード。
この色は、比較的「暗い色」なのか?「明るい色」なのか?

使う場面

背景色を「#4631b9」にした場合、文字は「白」が良いか?「黒」が良いか?

背景色を動的に変える場合、自動で判定したい。

公式

( $r*0.299 + $g*0.587 + $b*0.114 ) / 2.55

明るい場合には100に近い値、暗い場合には0に近い値となる。

PHPコード

getLuminance.php
<?php

function getLuminance( $rgb ) {

    $r = hexdec( mb_substr( $rgb, 0, 2 ) ); 
    $g = hexdec( mb_substr( $rgb, 2, 2 ) );     
    $b = hexdec( mb_substr( $rgb, 4, 2 ) ); 

    return ( $r*299 + $g*587 + $b*114 ) / 2550;

}

echo getLuminance( "4631b9" );


真っ白#ffffffなら100、真っ黒#000000なら0が返る。

入力値が「4631b9」場合、約28の値が返る。つまり、#4631b9は比較的暗い色だから「文字には明るい白」が良い。

参考URL

https://fromkato.com/color/4631b9 ← #4631b9 は、この色

13
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
6