Skip to content

Instantly share code, notes, and snippets.

@devnix
Forked from mailtruck/colormeter.js
Last active May 16, 2020 00:26
Show Gist options
  • Save devnix/ed7953386814f023ea496f41209fd3cc to your computer and use it in GitHub Desktop.
Save devnix/ed7953386814f023ea496f41209fd3cc to your computer and use it in GitHub Desktop.
Calculate difference in percentage between 2 hex colors. Port from Javascript to PHP. For calculating the perception difference, may would be better https://github.com/renasboy/php-color-difference
<?php
function color_meter($cwith, $ccolor) {
if (empty($cwith) || empty($ccolor)) return false;
$_cwith = ($cwith[0] === '#') ? substr($cwith, 1, 7) : $cwith;
$_ccolor = ($ccolor[0] === '#') ? substr($ccolor, 1, 7) : $ccolor;
$_r = intval(substr($_cwith, 0, 2), 16);
$_g = intval(substr($_cwith, 2, 2), 16);
$_b = intval(substr($_cwith, 4, 2), 16);
$__r = intval(substr($_ccolor, 0, 2), 16);
$__g = intval(substr($_ccolor, 2, 2), 16);
$__b = intval(substr($_ccolor, 4, 2), 16);
$p1 = ($_r / 255) * 100;
$p2 = ($_g / 255) * 100;
$p3 = ($_b / 255) * 100;
$perc1 = round(($p1 + $p2 + $p3) / 3);
$p1 = ($__r / 255) * 100;
$p2 = ($__g / 255) * 100;
$p3 = ($__b / 255) * 100;
$perc2 = round(($p1 + $p2 + $p3) / 3);
return abs($perc1 - $perc2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment