Add ImageQuality class to hold quality values

This commit is contained in:
Harald Eilertsen
2025-10-13 18:43:13 +02:00
parent 2a3dc6cc50
commit 3c89c7d4f4
2 changed files with 98 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
<?php
/*
* SPDX-FileCopyrightText: 2025 The Hubzilla Community
* SPDX-FileContributor: Harald Eilertsen <haraldei@anduin.net>
*
* SPDX-License-Identifier: MIT
*/
namespace Zotlabs\Photo;
/**
* A class to represent image quality values.
*/
class ImageQuality
{
readonly string $mimeType;
readonly int $value;
private const DEFAULT_VALUE = [
'image/jpg' => JPEG_QUALITY,
'image/png' => PNG_QUALITY,
'image/avif' => AVIF_QUALITY,
'image/webp' => WEBP_QUALITY,
];
public function __construct(string $mimeType, int $value) {
[ $min, $max ] = $this->validRange($mimeType);
if ($value < $min || $value > $max) {
$value = self::DEFAULT_VALUE[$mimeType];
}
$this->value = $value;
$this->mimeType = $mimeType;
}
/**
* Return the valid quality setting range for the given mime type.
*
* @param string $mimeType The mime type whose range to return.
*
* @return The valid range as an array with two elements as
* [ $min, $max ].
*/
public static function validRange(string $mimeType): array {
// Max quality for PNG is 10, for all others it's 100.
return $mimeType === 'image/png' ? [ 0, 10 ] : [ 1, 100 ];
}
}

View File

@@ -0,0 +1,49 @@
<?php
/*
* SPDX-FileCopyrightText: 2025 The Hubzilla Community
* SPDX-FileContributor: Harald Eilertsen <haraldei@anduin.net>
*
* SPDX-License-Identifier: MIT
*/
namespace Zotlabs\Tests\Unit\Photo;
use PHPUnit\Framework\Attributes\TestWith;
use Zotlabs\Photo\ImageQuality;
use Zotlabs\Tests\Unit\UnitTestCase;
class ImageQualityTest extends UnitTestCase
{
private const DEFAULT_VALUE = [
'image/jpg' => JPEG_QUALITY,
'image/png' => PNG_QUALITY,
'image/avif' => AVIF_QUALITY,
'image/webp' => WEBP_QUALITY,
];
#[TestWith(['image/jpg', 55])]
#[TestWith(['image/jpg', 100])]
#[TestWith(['image/png', 8])]
#[TestWith(['image/png', 0])]
#[TestWith(['image/avif', 99])]
#[TestWith(['image/webp', 1])]
public function testConstructWithValidValues(string $mimeType, int $value): void {
$q = new ImageQuality($mimeType, $value);
$this->assertEquals($value, $q->value);
}
#[TestWith(['image/jpg', 0])]
#[TestWith(['image/jpg', 101])]
#[TestWith(['image/png', -1])]
#[TestWith(['image/png', 11])]
#[TestWith(['image/avif', 0])]
#[TestWith(['image/avif', 101])]
#[TestWith(['image/webp', 0])]
#[TestWith(['image/webp', 101])]
public function testConstructWithOutOfBoundsValueReplacedWithDefault(
string $mimeType, int $value
): void {
$q = new ImageQuality($mimeType, $value);
$this->assertEquals(self::DEFAULT_VALUE[$mimeType], $q->value);
}
}