Skip to content

Instantly share code, notes, and snippets.

@Boztown
Last active July 19, 2019 10:47
Show Gist options
  • Save Boztown/8060706 to your computer and use it in GitHub Desktop.
Save Boztown/8060706 to your computer and use it in GitHub Desktop.
Here's a little function in C# to resize an image with proportional constraints. Just specific the max width and max height and this method will return a bitmap all sized up for you. I have this snipped in the form of a static **Utilities** class because that's how I use it.
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Drawing;
namespace Utilities
{
public static class ImageProcessingUtility
{
/// <summary>
/// Scales an image proportionally. Returns a bitmap.
/// </summary>
/// <param name="image"></param>
/// <param name="maxWidth"></param>
/// <param name="maxHeight"></param>
/// <returns></returns>
static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
return bmp;
}
}
}
@Bogdaan
Copy link

Bogdaan commented May 24, 2016

👎 not works with DPI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment