MagickImageMetadataReader.php: update to read exif orientation

This commit is contained in:
Zankaria 2025-03-22 00:35:41 +01:00
parent a683ce2bf8
commit 2ff248cd3b

View file

@ -1,41 +1,70 @@
<?php
namespace Vichan\Service\Media;
use Vichan\Data\ImageMetadataResult;
use Mimey\MimeTypes;
use Vichan\Data\{Exif, ImageMetadataResult};
use Vichan\Functions\Mime;
class MagickImageMetadataReader implements ImageMetadataReader {
private string $prefix;
private MimeTypes $mime_types;
public static function createImageMagickReader(MimeTypes $mime_types): MagickImageMetadataReader {
return new self('', $mime_types);
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 createGraphicsMagickReader(MimeTypes $mime_types): MagickImageMetadataReader {
return new self('gm ', $mime_types);
public static function createImageMagickReader(): MagickImageMetadataReader {
return new self('magick');
}
private function __construct(string $prefix, MimeTypes $mime_types) {
public static function createGraphicsMagickReader(): MagickImageMetadataReader {
return new self('gm');
}
private function __construct(string $prefix) {
$this->prefix = $prefix;
$this->mime_types = $mime_types;
}
public function getMetadata(string $file_path): ImageMetadataResult {
$arg = \escapeshellarg("$file_path[0]");
$ret_exec = shell_exec_error("{$this->prefix}identify -format \"%w %h %m\" $arg");
$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]+)$/', $ret_exec, $m);
$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 = $this->mime_types->getMimeType($m[3]) ?? 'application/octet-stream';
return new ImageMetadataResult($m[1], $m[2], $mime);
$mime = Mime\ext_to_mime($ext) ?? 'application/octet-stream';
$exif_orientation = self::parseOrientation($orientation_str);
return new ImageMetadataResult($width, $height, $mime, $exif_orientation);
}
}