c# Image resizing to different size while preserving aspect ratio
I found out how to resize AND pad the image by learning from this this CodeProject Article.
static Image FixedSize(Image imgPhoto, int Width, int Height)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((Width -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((Height -
(sourceHeight * nPercent)) / 2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(Width, Height,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.Red);
grPhoto.InterpolationMode =
InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
How to resize an image maintaining the aspect ratio in C#
//calculate the ratio
double dbl = (double)image.Width / (double)image.Height;
//set height of image to boxHeight and check if resulting width is less than boxWidth,
//else set width of image to boxWidth and calculate new height
if( (int)((double)boxHeight * dbl) <= boxWidth )
{
resizedImage = new Bitmap(original, (int)((double)boxHeight * dbl), boxHeight);
}
else
{
resizedImage = new Bitmap(original, boxWidth, (int)((double)boxWidth / dbl) );
}
The formula for scaling with the same ratio is:
newWidth = (int)((double)boxHeight * dbl)
or
newHeight = (int)((double)boxWidth / dbl)
Resize Image while maintaining aspect ratio
Image thumb = image.GetThumbnailImage(image.Width / 2, image.Height / 2, null, IntPtr.Zero);
image.Dispose();
How to resize my image and maintain the aspect ratio?
Let (W, H)
be the size of your image. Let s = max(W, H)
. Then you want to resize the image to (w, h) = (640 * W / s, 640 * H / s)
where /
denotes integer division. Note that we have w <= 640
and h <= 640
and max(w, h) = 640
.
The horizontal and vertical offsets for your image inside of the new (640, 640)
image are x = (640 - W) / 2
and y = (640 - H) / 2
, respectively.
You can accomplish all of this by creating a new (640, 640)
blank white image and then drawing your current image to the rectangle (x, y, w, h)
.
var sourcePath = textBox1.Text;
var destinationSize = 640;
using (var destinationImage = new Bitmap(destinationSize, destinationSize))
{
using (var graphics = Graphics.FromImage(destinationImage))
{
graphics.Clear(Color.White);
using (var sourceImage = new Bitmap(sourcePath))
{
var s = Math.Max(sourceImage.Width, sourceImage.Height);
var w = destinationSize * sourceImage.Width / s;
var h = destinationSize * sourceImage.Height / s;
var x = (destinationSize - w) / 2;
var y = (destinationSize - h) / 2;
// Use alpha blending in case the source image has transparencies.
graphics.CompositingMode = CompositingMode.SourceOver;
// Use high quality compositing and interpolation.
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(sourceImage, x, y, w, h);
}
}
destinationImage.Save(...);
}
Resize image in C# with aspect ratio and crop central image so there are no gaps
You should pass needToFill = true:
public static System.Drawing.Image FixedSize(Image image, int Width, int Height, bool needToFill)
{
#region calculations
int sourceWidth = image.Width;
int sourceHeight = image.Height;
int sourceX = 0;
int sourceY = 0;
double destX = 0;
double destY = 0;
double nScale = 0;
double nScaleW = 0;
double nScaleH = 0;
nScaleW = ((double)Width / (double)sourceWidth);
nScaleH = ((double)Height / (double)sourceHeight);
if (!needToFill)
{
nScale = Math.Min(nScaleH, nScaleW);
}
else
{
nScale = Math.Max(nScaleH, nScaleW);
destY = (Height - sourceHeight * nScale) / 2;
destX = (Width - sourceWidth * nScale) / 2;
}
if (nScale > 1)
nScale = 1;
int destWidth = (int)Math.Round(sourceWidth * nScale);
int destHeight = (int)Math.Round(sourceHeight * nScale);
#endregion
System.Drawing.Bitmap bmPhoto = null;
try
{
bmPhoto = new System.Drawing.Bitmap(destWidth + (int)Math.Round(2 * destX), destHeight + (int)Math.Round(2 * destY));
}
catch (Exception ex)
{
throw new ApplicationException(string.Format("destWidth:{0}, destX:{1}, destHeight:{2}, desxtY:{3}, Width:{4}, Height:{5}",
destWidth, destX, destHeight, destY, Width, Height), ex);
}
using (System.Drawing.Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto))
{
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.CompositingQuality = CompositingQuality.HighQuality;
grPhoto.SmoothingMode = SmoothingMode.HighQuality;
Rectangle to = new System.Drawing.Rectangle((int)Math.Round(destX), (int)Math.Round(destY), destWidth, destHeight);
Rectangle from = new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight);
//Console.WriteLine("From: " + from.ToString());
//Console.WriteLine("To: " + to.ToString());
grPhoto.DrawImage(image, to, from, System.Drawing.GraphicsUnit.Pixel);
return bmPhoto;
}
}
Resize Image and retaining aspect ratio
You can query the image properties for height and width and determine aspect ration. If you then know either height or width, you can calculate the other value. Your need to add querying these properties to your code and then a little math.
Resize Image without Keeping Aspect Ratio
Remove all the calculations and use
grPhoto.DrawImage(imgPhoto,
new Rectangle(0, 0, newWidth, newHeight),
new Rectangle(0, 0, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
Here is the whole method:
public static Image Resize(Image source, int width, int height)
{
if (source.Width == width && source.Height == height) return source;
var result = new Bitmap(width, height, PixelFormat.Format24bppRgb);
result.SetResolution(source.HorizontalResolution, source.VerticalResolution);
using (var g = Graphics.FromImage(result))
g.DrawImage(source, new Rectangle(0, 0, width, height), new Rectangle(0, 0, source.Width, source.Height), GraphicsUnit.Pixel);
return result;
}
Image Getting Stretched when trying to Resize It keeping the aspect Ratio
Try this, its a bit neater
public static Bitmap ResizeImage(Bitmap source, Size size)
{
var scale = Math.Min(size.Width / (double)source.Width, size.Height / (double)source.Height);
var bmp = new Bitmap((int)(source.Width * scale), (int)(source.Height * scale));
using (var graph = Graphics.FromImage(bmp))
{
graph.InterpolationMode = InterpolationMode.High;
graph.CompositingQuality = CompositingQuality.HighQuality;
graph.SmoothingMode = SmoothingMode.AntiAlias;
graph.DrawImage(source, 0, 0, bmp.Width, bmp.Height);
}
return bmp;
}
Related Topics
How to Fix the Microsoft Visual Studio Error: "Package Did Not Load Correctly"
Memory Address of an Object in C#
Showing a Windows Form on a Secondary Monitor
C# Using Parameters.Addwithvalue in SQLdataadapter
How to Get a Human-Readable File Size in Bytes Abbreviation Using .Net
Understanding Async/Await in C#
List<T> VS Bindinglist<T> Advantages/Disadvantages
Playing a Mp3 File in a Winform Application
Serialize Dictionary as Array (Of Key Value Pairs)
.Net Xml Serialization Gotchas
Dynamically Adding Properties to an Expandoobject
Regex to Strip Line Comments from C#
Pass-Through Mouse Events to Parent Control
Install a .Net Windows Service Without Installutil.Exe
A Simple C# Dll - How to Call It from Excel, Access, Vba, Vb6