Last active
March 2, 2017 08:35
-
-
Save doeringp/e786061741904af8aa50bb938669a3a0 to your computer and use it in GitHub Desktop.
Creating thumbnail images with .NET's System.Drawing classes.
This file contains 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.Drawing.Imaging; | |
using System.Linq; | |
namespace ImageManipulation | |
{ | |
/// <summary> | |
/// Helper for manipulating images. Resizing images and creating thumbnails. | |
/// </summary> | |
public static class ImageManipulation | |
{ | |
public static void SaveThumbnail(string imageFilePath, string thumbnailFilePath, int maxWidth, int maxHeight) | |
{ | |
using (Image image = Image.FromFile(imageFilePath)) | |
{ | |
if (image.Width <= maxWidth && image.Height <= maxHeight) | |
{ | |
SaveImage(image, thumbnailFilePath); | |
} | |
else | |
{ | |
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); | |
using (Image thumbnail = Resize(image, newWidth, newHeight)) | |
{ | |
SaveImage(thumbnail, thumbnailFilePath); | |
} | |
} | |
} | |
} | |
public static Image Resize(this Image srcImage, int newWidth, int newHeight) | |
{ | |
Bitmap newImage = new Bitmap(newWidth, newHeight); | |
using (Graphics gr = Graphics.FromImage(newImage)) | |
{ | |
gr.SmoothingMode = SmoothingMode.HighQuality; | |
gr.InterpolationMode = InterpolationMode.HighQualityBicubic; | |
gr.PixelOffsetMode = PixelOffsetMode.HighQuality; | |
gr.CompositingQuality = CompositingQuality.HighQuality; | |
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight)); | |
} | |
return newImage; | |
} | |
public static void SaveImage(this Image image, string fileName, int quality = 95) | |
{ | |
string fileExtension = fileName.Split('.').Last().Replace("jpg", "jpeg"); | |
ImageCodecInfo codecInfo = ImageCodecInfo.GetImageEncoders() | |
.First(x => x.MimeType.EndsWith(fileExtension, StringComparison.InvariantCultureIgnoreCase)); | |
var encoderParams = new EncoderParameters | |
{ | |
Param = {[0] = new EncoderParameter(Encoder.Quality, quality)} | |
}; | |
image.Save(fileName, codecInfo, encoderParams); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment