using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Linq; using System.Web; namespace Default { public class ImageHelper { private static int DoubleToIntDef(double d, int def) { try { return Convert.ToInt32(d); } catch (Exception) { return def; } } public static Size GetImageContainSize(Size currentSize, Size maxSize, bool scaleUp = false) { Size newSize = currentSize; double ratioX = Convert.ToDouble(maxSize.Width) / Convert.ToDouble(currentSize.Width); double ratioY = Convert.ToDouble(maxSize.Height) / Convert.ToDouble(currentSize.Height); double ratio = System.Math.Min(ratioX, ratioY); if (ratio < 1.0 || scaleUp) { newSize.Width = DoubleToIntDef(Math.Floor(Convert.ToDouble(currentSize.Width) * ratio), 0); newSize.Height = DoubleToIntDef(Math.Floor(Convert.ToDouble(currentSize.Height) * ratio), 0); } return newSize; } public static Bitmap ResizeImage(Image image, int width, int height) { var destRect = new Rectangle(0, 0, width, height); var destImage = new Bitmap(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width,image.Height, GraphicsUnit.Pixel, wrapMode); } } return destImage; } } }
89200cookie-checkC# Resize Images