Skip to content

Instantly share code, notes, and snippets.

@kRapaille
Created June 30, 2014 15:03
Show Gist options
  • Save kRapaille/9721d0da2d8ea72af8eb to your computer and use it in GitHub Desktop.
Save kRapaille/9721d0da2d8ea72af8eb to your computer and use it in GitHub Desktop.
Fail when doing it 2 times on a same image.
// Based on : http://www.codeproject.com/Articles/2941/Resizing-a-Photographic-image-with-GDI-for-NET
private static void ScaleAndSaveImage(ImageResizeConfiguration config)
{
using (var fileStream = new FileStream(config.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var image = Image.FromStream(fileStream))
{
var sourceWidth = image.Width;
var sourceHeight = image.Height;
var destX = 0;
var destY = 0;
float nPercent;
var nPercentW = ((float) config.Width/sourceWidth);
var nPercentH = ((float) config.Height/sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = Convert.ToInt16((config.Width - (sourceWidth*nPercent))/2);
}
else
{
nPercent = nPercentW;
destY = Convert.ToInt16((config.Height - (sourceHeight*nPercent))/2);
}
var destWidth = (int) (sourceWidth*nPercent);
var destHeight = (int) (sourceHeight*nPercent);
using (var newImage = new Bitmap(config.Width, config.Height, PixelFormat.Format24bppRgb))
{
newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var grPhoto = Graphics.FromImage(newImage))
{
grPhoto.Clear(Color.FromName(config.BackgroundColorName));
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(image,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(0, 0, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
}
var fileName = config.FileName.Substring(0,config.FileName.Length - config.Extension.Length);
fileName = string.Format("{0}.{1}", fileName, config.TargetFormatText);
fileName = Path.Combine(config.TargetDirectory, fileName);
newImage.Save(fileName, config.TargetFormat);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment