private string GenerateImage(string source_file, string cache_file, int resolution)
{
string extension = Path.GetExtension(source_file).ToLower();
using (Image source_image = Image.FromFile(source_file)) {
// Check the image dimensions
int width = source_image.Size.Width;
int height = source_image.Size.Height;
// Do we need to downscale the image?
if (width <= resolution) { // no, because the width of the source image is already less than the client width
return source_file;
}
// We need to resize the source image to the width of the resolution breakpoint we're working with
float ratio = (float)height / width;
int new_width = resolution;
int new_height = (int)Math.Ceiling(new_width * ratio);
using (Image scaled_image = new Bitmap(new_width, new_height)) {
using (Graphics graphics = Graphics.FromImage(scaled_image)) {
//Set interpolation mode, otherwise it looks rubbish.
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
//Draw the original image as a scaled image
graphics.DrawImage(source_image, new Rectangle(0, 0, new_width, new_height), new RectangleF(0, 0, width, height), GraphicsUnit.Pixel);
graphics.Flush();
}
//create cache directory if it doesn't exist
if (!Directory.Exists(Path.GetDirectoryName(cache_file)))
Directory.CreateDirectory(Path.GetDirectoryName(cache_file));
//save image in appropriate format
switch (extension) {
case ".png":
scaled_image.Save(cache_file, ImageFormat.Png);
break;
case ".gif":
scaled_image.Save(cache_file, ImageFormat.Gif);
break;
default:
EncoderParameters ep = new EncoderParameters();
ep.Param[0] = new EncoderParameter(Encoder.Quality, jpg_quality);
scaled_image.Save(cache_file, GetEncoderForMimeType("image/jpeg"), ep);
break;
}
}
}
return cache_file;
}