public static Image ResizeAndFit(this Image image, Size newSize) { var sourceIsLandscape = image.Width > image.Height; var targetIsLandscape = newSize.Width > newSize.Height; var ratioWidth = (double)newSize.Width / (double)image.Width; var ratioHeight = (double)newSize.Height / (double)image.Height; var ratio = 0.0; if (ratioWidth > ratioHeight && sourceIsLandscape == targetIsLandscape) ratio = ratioWidth; else ratio = ratioHeight; int targetWidth = (int)(image.Width * ratio); int targetHeight = (int)(image.Height * ratio); var bitmap = new Bitmap(newSize.Width, newSize.Height); var graphics = Graphics.FromImage((Image)bitmap); graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; var offsetX = ((double)(newSize.Width - targetWidth)) / 2; var offsetY = ((double)(newSize.Height - targetHeight)) / 2; graphics.DrawImage(image, (int)offsetX, (int)offsetY, targetWidth, targetHeight); graphics.Dispose(); return (Image)bitmap; }
Monday, January 30, 2012
Best Extension Methods: Resize Image
If your site has more work on displaying product images then this extension method will best suit for you application. This extension method is able to resize the image.
Share This!
Labels:
C#.NET,
Extension Methods
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment