public byte[] SizeTo(byte[] imageBytes, ushort? width, ushort? height, ImageSizingBehavior behavior = ImageSizingBehavior.Fit) { // Must specify width or height if ((!width.HasValue || width.Value == 0) && (!height.HasValue || height.Value == 0)) throw new ArgumentNullException("Width or Height must be specified to resize the image"); // Create a new bitmap var bitmap = new Bitmap(new MemoryStream(imageBytes)); int actualWidth = width.HasValue ? width.Value : 0, actualHeight = height.HasValue ? height.Value : 0; // If either size is zero or behavior specifies to maintain the ratio if (actualWidth <= 0 || actualHeight <= 0 || (behavior & ImageSizingBehavior.MaintainAspectRatio) == ImageSizingBehavior.MaintainAspectRatio) { // Calculate the ratio var ratio = Convert.ToDouble(bitmap.Width) / bitmap.Height; // Determine the width and height based on the ratio of the width to the height if (actualHeight == 0 || (actualWidth > 0 && ratio >= 1)) actualHeight = Convert.ToInt32(Math.Floor(Math.Round(actualWidth / ratio, 0))); else actualWidth = Convert.ToInt32(Math.Floor(Math.Round(actualHeight * ratio, 0))); } // If image is larger and behavior doesn't allow for reduction, return original image if ((bitmap.Width >= actualWidth || bitmap.Height >= actualHeight) && (behavior & ImageSizingBehavior.Reduce) != ImageSizingBehavior.Reduce) return imageBytes; // If image is smaller and behavior doesn't allow for enlarging, return original image if ((bitmap.Width <= actualWidth || bitmap.Height <= actualHeight) && (behavior & ImageSizingBehavior.Enlarge) != ImageSizingBehavior.Enlarge) return imageBytes; return SizeTo(bitmap, actualWidth, actualHeight); }
public byte[] SizeTo(byte[] imageBytes, ushort widthOrHeight, ImageSizingBehavior behavior = ImageSizingBehavior.Fit) { // Force maintain the aspect ratio return SizeTo(imageBytes, widthOrHeight, widthOrHeight, behavior | ImageSizingBehavior.MaintainAspectRatio); }