leftypol/inc/Service/Media/MagickImageMetadataReader.php

41 lines
1.2 KiB
PHP
Raw Normal View History

<?php
namespace Vichan\Service\Media;
use Mimey\MimeTypes;
use Vichan\Data\ImageMetadataResult;
class MagickImageMetadataReader implements ImageMetadataReader {
private string $prefix;
private MimeTypes $mime_types;
public static function createImageMagickReader(MimeTypes $mime_types): MagickImageMetadataReader {
return new self('', $mime_types);
}
public static function createGraphicsMagickReader(MimeTypes $mime_types): MagickImageMetadataReader {
return new self('gm ', $mime_types);
}
private function __construct(string $prefix, MimeTypes $mime_types) {
$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");
if (!\is_string($ret_exec)) {
throw new \RuntimeException("Error while executing identify");
}
$ret_match = \preg_match('/^(\d+) (\d+) ([\w\d]+)$/', $ret_exec, $m);
if (!$ret_match) {
throw new \RuntimeException("Could not parse identify output");
}
$mime = $this->mime_types->getMimeType($m[3]) ?? 'application/octet-stream';
return new ImageMetadataResult($m[1], $m[2], $mime);
}
}