Skip to content

Instantly share code, notes, and snippets.

@A-Programmer
Created April 7, 2017 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A-Programmer/77ddd0a56f8e0919a2491be27f6e16da to your computer and use it in GitHub Desktop.
Save A-Programmer/77ddd0a56f8e0919a2491be27f6e16da to your computer and use it in GitHub Desktop.
Some methods for working with images in C#
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