<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Api;

class ImageApi
{
  private function __construct()
  {
  }

  
  public static function diffToWhite($img0, int $width, int $height): float
  {
    $whiteImg = imagecreate($width, $height);
    $white = imagecolorallocate($whiteImg, 0xFF, 0xFF, 0xFF);
    imagefilledrectangle($whiteImg, 0, 0, $width, $height, $white);

    return static::diff($img0, $whiteImg, $width, $height);
  }

  
  public static function diff($img0, $img1, int $width, int $height): float
  {
    $diffSum = 0.0;
    for ($x = 0; $x < $width; ++$x) {
      for ($y = 0; $y < $height; ++$y) {
        $b0 = imagecolorat($img0, $x, $y);
        $b1 = imagecolorat($img1, $x, $y);
        list('red' => $r0, 'green' => $g0, 'blue' => $b0, 'alpha' => $a0) = imagecolorsforindex($img0, $b0);
        list('red' => $r1, 'green' => $g1, 'blue' => $b1, 'alpha' => $a1) = imagecolorsforindex($img1, $b1);
        $c0 = ($r0 + $g0 + $b0) / 3.0;
        $c1 = ($r1 + $g1 + $b1) / 3.0;

        $v0 = ($c0 + $a0) / 2.0;
        $v1 = ($c1 + $a1) / 2.0;

        $diffSum += abs($v0 - $v1) / 255.0;
      }
    }

    return $diffSum / ($width * $height);
  }
}