SpritePacker/SpritePacker/SBRLUtilities/ResizeImage.cs

51 lines
1.4 KiB
C#
Executable File

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace SpritePacker.SBRLUtilities
{
public static partial class ImageTools
{
/// <summary>
/// Resizes a <c>Bitmap</c> such that it fits within the target dimensions.
/// </summary>
/// <description>
/// v0.1, by Starbeamrainbowlabs
/// Last updated on 2nd August 2016
/// Licensed under MPL v2.0.
///
/// Changelog:
/// v0.1 (2nd August 2016):
/// - Initial Release.
/// </description>
/// <param name="sourceImage">The image to resize.</param>
/// <param name="targetBox">The target dimensions.</param>
/// <returns>The resized image.</returns>
public static Bitmap ResizeImage(Bitmap sourceImage, Size targetBox)
{
float scaleFactor = Math.Min(
targetBox.Width / (float)sourceImage.Width,
targetBox.Height / (float)sourceImage.Height
);
Size thumbnailSize = new Size(
(int)(sourceImage.Width * scaleFactor),
(int)(sourceImage.Height * scaleFactor)
);
Bitmap resultImage = new Bitmap(thumbnailSize.Width, thumbnailSize.Height);
using (Graphics context = Graphics.FromImage(resultImage)) {
context.CompositingMode = CompositingMode.SourceCopy;
context.InterpolationMode = InterpolationMode.HighQualityBicubic;
context.DrawImage(sourceImage, new Rectangle(
Point.Empty,
thumbnailSize
));
}
return resultImage;
}
}
}