Last active
July 19, 2019 10:47
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👎 not works with DPI