Created
September 8, 2009 13:44
-
-
Save jpoehls/182920 to your computer and use it in GitHub Desktop.
ImageResizer
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.Drawing.Imaging; | |
using System.IO; | |
using System.Linq; | |
namespace Boo | |
{ | |
public class ImageResizer | |
{ | |
/// <summary> | |
/// Opens an image file, resizes it and returns the resized copy | |
/// as a stream. | |
/// </summary> | |
/// <param name="fileName">Name of the file.</param> | |
/// <param name="newWidth">Width of the image to create.</param> | |
/// <returns>Stream of the resized image file.</returns> | |
public static byte[] GetResizedImage(string fileName, int newWidth) | |
{ | |
var file = new FileInfo(fileName); | |
using (Image image = Image.FromFile(file.FullName)) | |
{ | |
using (var stream = new MemoryStream()) | |
{ | |
int newHeight = image.Height * newWidth / image.Width; | |
if (image.Width > newWidth && GraphicsSupportsPixelFormat(image.PixelFormat)) | |
{ | |
using (Image thumbnail = new Bitmap(newWidth, newHeight, image.PixelFormat)) | |
{ | |
Graphics thumbGraph = Graphics.FromImage(thumbnail); | |
thumbGraph.CompositingQuality = CompositingQuality.HighQuality; | |
thumbGraph.SmoothingMode = SmoothingMode.HighQuality; | |
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; | |
var rect = new Rectangle(0, 0, newWidth, newHeight); | |
thumbGraph.DrawImage(image, rect); | |
thumbnail.Save(stream, ImageFormat.Jpeg); | |
} | |
} | |
else | |
{ | |
image.Save(stream, ImageFormat.Jpeg); | |
} | |
byte[] content = stream.ToArray(); | |
return content; | |
} | |
} | |
} | |
private static bool GraphicsSupportsPixelFormat(PixelFormat format) | |
{ | |
// these pixel formats are not supported by the Graphics.FromImage() method | |
// http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx | |
if (format == PixelFormat.Format1bppIndexed || | |
format == PixelFormat.Format4bppIndexed || | |
format == PixelFormat.Format8bppIndexed || | |
format == PixelFormat.Undefined || | |
format == PixelFormat.DontCare || | |
format == PixelFormat.Format16bppArgb1555 || | |
format == PixelFormat.Format16bppGrayScale) | |
{ | |
return false; | |
} | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment