leftypol/inc/Service/Media/CmdMagickImageMetadataReader.php

71 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace Vichan\Service\Media;
use Vichan\Data\{Exif, ImageMetadataResult};
use Vichan\Functions\Mime;
class CmdMagickImageMetadataReader implements ImageMetadataReader {
private string $prefix;
2025-03-18 10:23:01 +01:00
private static function parseOrientation(string $str): ?int {
switch ($str) {
case 'Undefined':
return Exif::EXIF_ORIENTATION_UNDEFINED;
case 'TopLeft':
return Exif::EXIF_ORIENTATION_0_UPRIGHT;
case 'TopRight':
return Exif::EXIF_ORIENTATION_0_FLIPPED;
case 'BottomRight':
return Exif::EXIF_ORIENTATION_180_UPRIGHT;
case 'BottomLeft':
return Exif::EXIF_ORIENTATION_180_FLIPPED;
case 'LeftTop':
return Exif::EXIF_ORIENTATION_90_UPRIGHT;
case 'RightTop':
return Exif::EXIF_ORIENTATION_90_FLIPPED;
case 'RightBottom':
return Exif::EXIF_ORIENTATION_270_UPRIGHT;
case 'LeftBottom':
return Exif::EXIF_ORIENTATION_270_FLIPPED;
case 'Unrecognized':
default:
return null;
}
}
public static function createImageMagickReader(): self {
return new self('magick');
}
public static function createGraphicsMagickReader(): self {
return new self('gm');
}
private function __construct(string $prefix) {
$this->prefix = $prefix;
}
public function getMetadata(string $file_path): ImageMetadataResult {
2025-03-18 10:23:01 +01:00
$arg = \escapeshellarg("$file_path[0]");
$ret_exec = shell_exec_error("{$this->prefix} identify -format \"%w %h %m\" $arg");
if (!\is_string($ret_exec)) {
throw new \RuntimeException('Error while executing identify');
}
$ret_match = \preg_match('/^(\d+) (\d+) ([\w\d]+) ([\w]+)$/', $ret_exec, $m);
if (!$ret_match) {
throw new \RuntimeException('Could not parse identify output');
}
$width = $m[1];
$height = $m[2];
$ext = $m[3];
$orientation_str = $m[4];
$mime = Mime\ext_to_mime($ext) ?? 'application/octet-stream';
$exif_orientation = self::parseOrientation($orientation_str);
return new ImageMetadataResult($width, $height, $mime, $exif_orientation);
}
}