From 6d03a2582e262a6845b3b436b02a4909ef3af7a3 Mon Sep 17 00:00:00 2001
From: regs01 <megaone@yandex.ru>
Date: Wed, 25 Sep 2024 18:19:12 +0000
Subject: [PATCH] SetSize with output dimensions depending on orientation

---
 packages/fcl-image/src/fpreadjpeg.pas | 45 ++++++++++++++++-----------
 1 file changed, 26 insertions(+), 19 deletions(-)

diff --git a/packages/fcl-image/src/fpreadjpeg.pas b/packages/fcl-image/src/fpreadjpeg.pas
index 4bd56cff37..4b55fabe62 100644
--- a/packages/fcl-image/src/fpreadjpeg.pas
+++ b/packages/fcl-image/src/fpreadjpeg.pas
@@ -217,31 +217,16 @@ begin
 end;
 
 procedure TFPReaderJPEG.ReadHeader(Str: TStream; Img: TFPCustomImage);
-var
-   S: TSize;
-
-  function TranslateSize(const Sz: TSize): TSize;
-  begin
-    case FOrientation of
-      eoUnknown, eoNormal, eoMirrorHor, eoMirrorVert, eoRotate180: Result := Sz;
-      eoMirrorHorRot270, eoRotate90, eoMirrorHorRot90, eoRotate270:
-      begin
-        Result.Width := Sz.Height;
-        Result.Height := Sz.Width;
-      end;
-    end;
-  end;
-
 begin
   jpeg_read_header(@FInfo, TRUE);
 
+  FWidth := FInfo.image_width;
+  FHeight := FInfo.image_height;  
+
   if FInfo.saw_EXIF_marker and (FInfo.orientation >= Ord(Low(TExifOrientation))) and (FInfo.orientation <= Ord(High(TExifOrientation))) then
     FOrientation := TExifOrientation(FInfo.orientation)
   else
     FOrientation := Low(TExifOrientation);
-  S := TranslateSize(TSize.Create(FInfo.image_width, FInfo.image_height));
-  FWidth := S.Width;
-  FHeight := S.Height;
 
   FGrayscale := FInfo.jpeg_color_space = JCS_GRAYSCALE;
   FProgressiveEncoding := jpeg_has_multiple_scans(@FInfo);
@@ -262,6 +247,7 @@ var
   c: word;
   Status,Scan: integer;
   ReturnValue,RestartLoop: Boolean;
+  LOutputSize: TSize;
 
   procedure InitReadingPixels;
   var d1,d2:integer;
@@ -460,6 +446,24 @@ var
       inc(y);
     end;
   end;
+
+  function TranslateSize(AWidth, AHeight: Integer): TSize;
+  begin
+    // image dimension depending on orientation
+    case FOrientation of
+      eoUnknown, eoNormal, eoMirrorHor, eoRotate180, eoMirrorVert:
+      begin
+        Result.Width := AWidth;
+        Result.Height := AHeight;
+      end;
+      eoMirrorHorRot270, eoRotate90,  eoMirrorHorRot90, eoRotate270:
+      begin
+        Result.Width := AHeight;
+        Result.Height := AWidth;
+      end;
+    end;
+  end;   
+
 begin
   InitReadingPixels;
 
@@ -469,7 +473,10 @@ begin
 
   jpeg_start_decompress(@FInfo);
 
-  Img.SetSize(FWidth,FHeight);
+  LOutputSize := TranslateSize(FInfo.output_width, FInfo.output_height);
+  FWidth := LOutputSize.Width;
+  FHeight := LOutputSize.Height;
+  Img.SetSize(FWidth, FHeight);
 
   GetMem(SampArray,SizeOf(JSAMPROW));
   GetMem(SampRow,FInfo.output_width*FInfo.output_components);