Skip to content

Instantly share code, notes, and snippets.

@ModernHooman
Created March 6, 2018 11:53
Show Gist options
  • Save ModernHooman/95b5801127e819f5177ec929c5cf91b9 to your computer and use it in GitHub Desktop.
Save ModernHooman/95b5801127e819f5177ec929c5cf91b9 to your computer and use it in GitHub Desktop.
A function/method to change dimensions of an Image in C#
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace ConsoleApplication {
public class ImageEditor {
/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static Bitmap Resize(Image image, int width, int height) {
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage)) {
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes()) {
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
/// <summary>
/// Converts an array of bytes to an Image instance
/// </summary>
/// <param name="bytes">The array of bytes to convert to Image instance.</param>
/// <returns>The Image instance.</returns>
public static Image BytesToImage(byte[] bytes) {
Image img;
using (MemoryStream ms = new MemoryStream(bytes)) {
img = Image.FromStream(ms);
}
return img;
}
/// <summary>
/// Saves a Bitmap instance to a file.
/// </summary>
/// <param name="bitmap">The Bitmap to save.</param>
/// <param name="path">The path to save to.</param>
/// <param name="nameWithExtension">The file's name to save.</param>
/// <param name="imageFormat">The ImageFormat to save as.</param>
public static void SaveToPath(Bitmap bitmap, string path, string nameWithExtension, ImageFormat imageFormat) {
bitmap.Save(path + nameWithExtension, imageFormat);
bitmap.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment