AC.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. <?php
  2. namespace App\Util\Blurhash;
  3. final class AC {
  4. public static function encode(array $value, float $max_value): float {
  5. $quant_r = static::quantise($value[0] / $max_value);
  6. $quant_g = static::quantise($value[1] / $max_value);
  7. $quant_b = static::quantise($value[2] / $max_value);
  8. return $quant_r * 19 * 19 + $quant_g * 19 + $quant_b;
  9. }
  10. public static function decode(int $value, float $max_value): array {
  11. $quant_r = floor($value / (19 * 19));
  12. $quant_g = floor($value / 19) % 19;
  13. $quant_b = $value % 19;
  14. return [
  15. static::signPow(($quant_r - 9) / 9, 2) * $max_value,
  16. static::signPow(($quant_g - 9) / 9, 2) * $max_value,
  17. static::signPow(($quant_b - 9) / 9, 2) * $max_value
  18. ];
  19. }
  20. private static function quantise(float $value): float {
  21. return floor(max(0, min(18, floor(static::signPow($value, 0.5) * 9 + 9.5))));
  22. }
  23. private static function signPow(float $base, float $exp): float {
  24. $sign = $base <=> 0;
  25. return $sign * pow(abs($base), $exp);
  26. }
  27. }