TPLLimited
asked on
C# .net Image Resizer
Hi
I have the following piece of code which resizes images to 620 pixels wide by 414 pixels high
Problem is when someone uploads a picture say 309 pixels wide by 414 pixels high it stretches the image to 620 pixels wide.
Anyone know how to amend this so if the width of a picture is less that 620 pixels wide it adds white space to either side of the image?
Thanks in advance
I have the following piece of code which resizes images to 620 pixels wide by 414 pixels high
Problem is when someone uploads a picture say 309 pixels wide by 414 pixels high it stretches the image to 620 pixels wide.
Anyone know how to amend this so if the width of a picture is less that 620 pixels wide it adds white space to either side of the image?
Thanks in advance
using System.Drawing;
using System.Drawing.Drawing2D;
public class ImageResizer
{
public static Image ResizeImage(Image image, Size size, bool preserveAspectRatio)
{
int newWidth;
int newHeight;
if (preserveAspectRatio)
{
int originalWidth = image.Width;
int originalHeight = image.Height;
float percentWidth = (float)size.Width / (float)originalWidth;
float percentHeight = (float)size.Height / (float)originalHeight;
float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
newWidth = (int)(originalWidth * percent);
newHeight = (int)(originalHeight * percent);
}
else
{
newWidth = size.Width;
newHeight = size.Height;
}
Image newImage = new Bitmap(newWidth, newHeight);
using (Graphics graphicsHandle = Graphics.FromImage(newImage))
{
graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.