using System.Drawing;
using System.IO;
namespace WebPages.Bll
{
public class GraphicUtilities
{
const int DEFAULT_THUMBNAIL_PIXEL_WIDTH = 64;
const int DEFAULT_THUMBNAIL_PIXEL_HEIGHT = 64;
///
/// Creates a thumbnail image using the default thumbnail size. Image aspect ratio is respected
///
/// Source image
/// The thumbnail image
public Stream CreateThumbnail(Stream sourceImage)
{
return ResizeImage(sourceImage, true, DEFAULT_THUMBNAIL_PIXEL_WIDTH, DEFAULT_THUMBNAIL_PIXEL_HEIGHT);
}
///
/// Resizes an image
///
/// Source image to process
/// If true then image aspect ratio is respected, if false the image may be stretched to fit the given width and height
/// New image width
/// New image height
/// The resized image
public Stream ResizeImage(Stream sourceImage, bool keepAspectRatio, int maxPixelWidth, int maxPixelHeight)
{
var orig = new Bitmap(sourceImage);
int width;
int height;
if (keepAspectRatio)
{
if (orig.Width > orig.Height)
{
width = maxPixelWidth;
height = maxPixelWidth * orig.Height / orig.Width;
}
else
{
height = maxPixelHeight;
width = maxPixelHeight * orig.Width / orig.Height;
}
}
else
{
width = maxPixelWidth;
height = maxPixelHeight;
}
var thumbnailImage = new Bitmap(width, height);
using (var graphic = Graphics.FromImage(thumbnailImage))
{
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphic.DrawImage(orig, 0, 0, width, height);
var stream = new MemoryStream();
thumbnailImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
}
}
}