leftypol/inc/Service/Media/DefaultImageMetadataReader.php

50 lines
1.6 KiB
PHP

<?php
namespace Vichan\Service\Media;
use Vichan\Data\Driver\Metadata\ExifReaderFactory;
use Vichan\Data\{Exif, ImageMetadataResult};
/**
* Do not use this if you can.
*
* Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be
* able to properly determine the image size. getimagesize() will return zero for width and height in these cases.
*
* The implementation only supports a limited subset of metadata for only the provided exif image formats readers.
* It won't always be able to correct the orientation, but it will try.
*/
class DefaultImageMetadataReader implements ImageMetadataReader {
private ExifReaderFactory $exif_reader_factory;
public function __construct(ExifReaderFactory $exif_reader_factory) {
$this->exif_reader_factory = $exif_reader_factory;
}
public function getMetadata(string $file_path): ImageMetadataResult {
$ret = \getimagesize($file_path, $info);
if ($ret === false) {
throw new \RuntimeException("Could not read image sizes of '$file_path'");
}
if ($ret[2] == \IMAGETYPE_UNKNOWN) {
throw new \RuntimeException("Error '$file_path' is not an image");
}
$width = $ret[0];
$height = $ret[1];
$mime = $ret['mime'];
$orientation = null;
$exif_reader = $this->exif_reader_factory->getReader($mime);
if ($exif_reader !== null) {
$orientation = $exif_reader->getOrientation($file_path);
if ($orientation !== null && Exif::exifOrientationOnSide($orientation)) {
$tmp = $width;
$width = $height;
$height = $tmp;
}
}
return new ImageMetadataResult($width, $height, $mime, $orientation);
}
}