Created
April 7, 2017 19:58
-
-
Save A-Programmer/77ddd0a56f8e0919a2491be27f6e16da to your computer and use it in GitHub Desktop.
Some methods for working with images in C#
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.Drawing; | |
using System.Drawing.Drawing2D; | |
using System.IO; | |
namespace Helpers | |
{ | |
public class ImageHelper | |
{ | |
/// <summary> | |
/// Resize and save an image to fit under width and height like a canvas keeping things proportional | |
/// </summary> | |
/// <param name="originalImagePath"></param> | |
/// <param name="thumbImagePath"></param> | |
/// <param name="newWidth"></param> | |
/// <param name="newHeight"></param> | |
public void GenerateThumbImage(string originalImagePath, string thumbImagePath, int newWidth, int newHeight) | |
{ | |
Bitmap srcBmp = new Bitmap(originalImagePath); | |
float ratio = 1; | |
float minSize = Math.Min(newHeight, newHeight); | |
if (srcBmp.Width > srcBmp.Height) | |
{ | |
ratio = minSize / (float)srcBmp.Width; | |
} | |
else | |
{ | |
ratio = minSize / (float)srcBmp.Height; | |
} | |
SizeF newSize = new SizeF(srcBmp.Width * ratio, srcBmp.Height * ratio); | |
Bitmap target = new Bitmap((int)newSize.Width, (int)newSize.Height); | |
using (Graphics graphics = Graphics.FromImage(target)) | |
{ | |
graphics.CompositingQuality = CompositingQuality.HighSpeed; | |
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; | |
graphics.CompositingMode = CompositingMode.SourceCopy; | |
graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height); | |
using (MemoryStream memoryStream = new MemoryStream()) | |
{ | |
target.Save(thumbImagePath); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment