From e47623cdf6ca68a459575d0134d5f1618c43156f Mon Sep 17 00:00:00 2001 From: Zankaria Date: Sat, 22 Mar 2025 01:40:30 +0100 Subject: [PATCH] GdMediaHandler.php: correct exif orientation if possible --- inc/Service/Media/GdMediaHandler.php | 44 ++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/inc/Service/Media/GdMediaHandler.php b/inc/Service/Media/GdMediaHandler.php index 6defcd05..e51200ba 100644 --- a/inc/Service/Media/GdMediaHandler.php +++ b/inc/Service/Media/GdMediaHandler.php @@ -1,7 +1,7 @@ strip_redraw = $strip_redraw; + $this->image_metadate_reader = $image_metadate_reader; } public function supportsMime(string $mime): bool { @@ -145,10 +151,38 @@ class GdMediaHandler implements MediaHandler { } public function openHandle(string $file_path, string $file_mime, int $file_kind): mixed { + $metadata = $this->image_metadate_reader->getMetadata($file_path); + if ($file_mime !== $file_mime) { + throw new \RuntimeException("Mime mismatch on '$file_path'"); + } + $gd = self::imageCreateFrom($file_path, $file_mime); if ($gd === false) { throw new \RuntimeException("Could not open '$file_path'"); } + + // Fix the orientation once and for all. + if ($metadata->exif_orientation !== null) { + $degrees = Exif::exifOrientationDegrees($metadata->exif_orientation); + $flipped = Exif::exifOrientationIsFlipped($metadata->exif_orientation); + + if ($degrees !== 0) { + self::enableTransparency($gd, $file_mime); + $gd_other = \imagerotate($gd, $degrees, \imagecolorallocatealpha($gd, 0, 0, 0, 127)); + \imagedestroy($gd); + if ($gd_other === false) { + throw new \RuntimeException("Error while correcting rotation of '$file_path'"); + } + $gd = $gd_other; + } + + if ($flipped) { + if (!\imageflip($gd, \IMG_FLIP_HORIZONTAL)) { + throw new \RuntimeException("Error while correcting flipping of '$file_path'"); + } + } + } + return [ $gd, $file_path, $file_mime, $file_kind ]; }