/// <summary> /// Gets scaling dimensions. /// </summary> /// <param name="width"></param> /// <param name="maxWidth"></param> /// <param name="height"></param> /// <param name="maxHeight"></param> /// <returns></returns> private static ScaleDimensionHelper GetScaleDimensions(int width, int maxWidth, int height, int maxHeight) { ScaleDimensionHelper s = new ScaleDimensionHelper(); // width if (width <= maxWidth) { s.NewWidth = width; s.NewHeight = height; } else { s.NewWidth = maxWidth; s.ScaleFactor = s.NewWidth / (double)width; s.NewHeight = (int)(height * s.ScaleFactor); } // height if (maxHeight <= 0 || s.NewHeight <= maxHeight) { return(s); } s.ScaleFactor = maxHeight / (double)s.NewHeight; s.NewHeight = maxHeight; s.NewWidth = (int)(s.NewWidth * s.ScaleFactor); return(s); }
/// <summary> /// Resizes an image. /// Make sure that if you're pulling the source image from a stream, /// the stream remains open. /// </summary> /// <param name="img"></param> /// <param name="maxWidth"></param> /// <param name="maxHeight"></param> /// <returns></returns> public static byte[] ResizeImage(Image img, int maxWidth, int maxHeight = 0) { ScaleDimensionHelper s = GetScaleDimensions(img.Width, maxWidth, img.Height, maxHeight); Rectangle imgRect = CreateRectangleFromDimensions(s); Bitmap bmp = CreateBitmapFromDimensions(s.NewWidth, s.NewHeight); DrawResizeOntoBitmap(bmp, img, imgRect); byte[] imgBytes = GetImageBytes(bmp, img.RawFormat); return(imgBytes); }
private static Rectangle CreateRectangleFromDimensions(ScaleDimensionHelper s) { Rectangle area = new Rectangle(0, 0, s.NewWidth, s.NewHeight); return(area); }