swf2ass/src/Color.php

55 lines
1.7 KiB
PHP

<?php
namespace swf2ass;
class Color {
public $r;
public $g;
public $b;
public $alpha;
public function __construct($r, $g, $b, $alpha = 255) {
$this->r = $r;
$this->g = $g;
$this->b = $b;
$this->alpha = $alpha;
}
public function equals(?Color $other, $alpha = true): bool {
return $other !== null and $other->r === $this->r and $other->g === $this->g and $other->b === $this->b and (!$alpha or $other->alpha == $this->alpha);
}
public function distance(Color $color, $alpha = false): float {
return sqrt(pow($color->r - $this->r, 2) + pow($color->g - $this->g, 2) + pow($color->b - $this->b, 2) + ($alpha ? pow($color->alpha - $this->alpha, 2) : 0));
}
public static function fromArray(array $element): Color {
return new Color($element["red"], $element["green"], $element["blue"], $element["alpha"] ?? 255);
}
public function __toString() : string{
return $this->toString(false);
}
public function toString(bool $noAlpha = false) : string{
return $noAlpha ? "rgb({$this->r},{$this->g},{$this->b})" : "rgba({$this->r},{$this->g},{$this->b},{$this->alpha})";
}
public function toLinearRGB() : Color{
return new Color(
pow($this->r / 255, 2.2) * 255,
pow($this->g / 255, 2.2) * 255,
pow($this->b / 255, 2.2) * 255,
pow($this->alpha / 255, 2.2) * 255,
);
}
public function tosRGB() : Color{
return new Color(
pow($this->r / 255, 0.4545) * 255,
pow($this->g / 255, 0.4545) * 255,
pow($this->b / 255, 0.4545) * 255,
pow($this->alpha / 255, 0.4545) * 255,
);
}
}