private static Rectangle GetImageCropRectangle(Size imgSize, Size cropSize, VerticalCropping verticalCropOption) { int x; int y; if (imgSize.Width != cropSize.Width) { throw new ArgumentException(string.Format ( "For a vertical crop, current width ({0}) must match desired cropped width ({1}).", imgSize.Width, cropSize.Width )); } else if (imgSize.Height < cropSize.Height) { throw new ArgumentException(string.Format ( "For a vertical crop, current height ({0}) must be greater than desired cropped height ({1}).", imgSize.Height, cropSize.Height )); } switch (verticalCropOption) { case VerticalCropping.Top: x = 0; y = 0; break; case VerticalCropping.Bottom: x = 0; y = imgSize.Height - cropSize.Height; break; default: // VerticalCropping.Center: x = 0; y = (imgSize.Height - cropSize.Height) / 2; break; } return(new Rectangle(x, y, cropSize.Width, cropSize.Height)); }
/// <summary> /// Resizes and crops the image to the given dimensions /// </summary> /// <param name="img">The image</param> /// <param name="width">The desired width</param> /// <param name="height">The desired height</param> /// <returns>The resized image</returns> public static Image Resize(Image img, int width, int height, HorizontalCropping cropH, VerticalCropping cropV) { // We only reduce size and crop, we don't magnify images if (!(img.Width == width && img.Height == height)) { if (width <= img.Width && height <= img.Height) { var xRecPos = 0; var yRecPos = 0; var xRatio = width / (double)img.Width; var yRatio = height / (double)img.Height; if (img.Height * xRatio < height) { img = Resize(img, Convert.ToInt32(img.Width * yRatio)); } else { img = Resize(img, Convert.ToInt32(width)); } if (cropH == HorizontalCropping.Center) { xRecPos = (img.Width - width) / 2; } else if (cropH == HorizontalCropping.Right) { xRecPos = img.Width - width; } if (cropV == VerticalCropping.Center) { yRecPos = (img.Height - height) / 2; } else if (cropV == VerticalCropping.Bottom) { yRecPos = img.Height - height; } var newRect = new Rectangle(xRecPos, yRecPos, width, height); var orgBmp = new Bitmap(img); var crpBmp = orgBmp.Clone(newRect, img.PixelFormat); orgBmp.Dispose(); return((Image)crpBmp); } } return(img); }