# HG changeset patch # User Sebastien Jodogne # Date 1592890763 -7200 # Node ID 2e1564f57542bb685bb76249e4d12053785b0d5c # Parent f18eaade61538527ad59135e591b2ed64b12b65c ImageProcessing::FitSizeKeepAspectRatio() diff -r f18eaade6153 -r 2e1564f57542 Core/Images/ImageProcessing.cpp --- 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 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(width) / static_cast(source.GetWidth()), + static_cast(height) / static_cast(source.GetHeight())); + + unsigned int resizedWidth = static_cast( + boost::math::iround(ratio * static_cast(source.GetWidth()))); + + unsigned int resizedHeight = static_cast( + boost::math::iround(ratio * static_cast(source.GetHeight()))); + + std::unique_ptr resized(FitSize(source, resizedWidth, resizedHeight)); + + ImageAccessor region; + target->GetRegion(region, (width - resizedWidth) / 2, + (height - resizedHeight) / 2, resizedWidth, resizedHeight); + Copy(region, *resized); + } + + return target.release(); + } } diff -r f18eaade6153 -r 2e1564f57542 Core/Images/ImageProcessing.h --- 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); }; } -