changeset 4082:2e1564f57542

ImageProcessing::FitSizeKeepAspectRatio()
author Sebastien Jodogne <s.jodogne@gmail.com>
date Tue, 23 Jun 2020 07:39:23 +0200
parents f18eaade6153
children 26efd0404d97 25812a487037
files Core/Images/ImageProcessing.cpp Core/Images/ImageProcessing.h
diffstat 2 files changed, 42 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/Core/Images/ImageProcessing.cpp	Mon Jun 22 19:04:09 2020 +0200
+++ b/Core/Images/ImageProcessing.cpp	Tue Jun 23 07:39:23 2020 +0200
@@ -2490,4 +2490,37 @@
     FitSize(*target, source);
     return target.release();
   }
+
+    
+  ImageAccessor* ImageProcessing::FitSizeKeepAspectRatio(const ImageAccessor& source,
+                                                         unsigned int width,
+                                                         unsigned int height)
+  {
+    std::unique_ptr<ImageAccessor> target(new Image(source.GetFormat(), width, height, false));
+    Set(*target, 0);
+
+    if (width != 0 &&
+        height != 0 &&
+        source.GetWidth() != 0 &&
+        source.GetHeight() != 0)
+    {
+      float ratio = std::min(static_cast<float>(width) / static_cast<float>(source.GetWidth()),
+                             static_cast<float>(height) / static_cast<float>(source.GetHeight()));
+
+      unsigned int resizedWidth = static_cast<unsigned int>(
+        boost::math::iround(ratio * static_cast<float>(source.GetWidth())));
+
+      unsigned int resizedHeight = static_cast<unsigned int>(
+        boost::math::iround(ratio * static_cast<float>(source.GetHeight())));
+
+      std::unique_ptr<ImageAccessor> resized(FitSize(source, resizedWidth, resizedHeight));
+
+      ImageAccessor region;
+      target->GetRegion(region, (width - resizedWidth) / 2,
+                        (height - resizedHeight) / 2, resizedWidth, resizedHeight);
+      Copy(region, *resized);
+    }
+
+    return target.release();
+  }
 }
--- a/Core/Images/ImageProcessing.h	Mon Jun 22 19:04:09 2020 +0200
+++ b/Core/Images/ImageProcessing.h	Tue Jun 23 07:39:23 2020 +0200
@@ -200,10 +200,17 @@
 
     static void FitSize(ImageAccessor& target,
                         const ImageAccessor& source);
-    
+
+    // Resize the image to the given width/height. The resized image
+    // occupies the entire canvas (aspect ratio is not preserved).
     static ImageAccessor* FitSize(const ImageAccessor& source,
                                   unsigned int width,
                                   unsigned int height);
+
+    // Resize an image, but keeps its original aspect ratio. Zeros are
+    // added around the image to reach the specified size.
+    static ImageAccessor* FitSizeKeepAspectRatio(const ImageAccessor& source,
+                                                 unsigned int width,
+                                                 unsigned int height);
   };
 }
-