Skip to content

Instantly share code, notes, and snippets.

@goyuix
Created November 20, 2012 01:23
Show Gist options
  • Save goyuix/4115351 to your computer and use it in GitHub Desktop.
Save goyuix/4115351 to your computer and use it in GitHub Desktop.
WPF Image Resize code for LINQPad
<Query Kind="Statements">
<Reference>&lt;RuntimeDirectory&gt;\System.Xaml.dll</Reference>
<Reference>&lt;RuntimeDirectory&gt;\WPF\WindowsBase.dll</Reference>
<Reference>&lt;RuntimeDirectory&gt;\WPF\PresentationCore.dll</Reference>
<Namespace>System.Windows.Media</Namespace>
<Namespace>System.Windows.Media.Imaging</Namespace>
</Query>
var ThumbnailSize = 800;
var source = @"C:\Users\Heather\Pictures\Canon SX230";
var dest = @"C:\Users\Heather\Desktop\SX230";
if (!Directory.Exists(dest)) { Directory.CreateDirectory(dest); }
foreach (var file in Directory.GetFiles(source, "*.jpg", SearchOption.AllDirectories))
{
using (var s = new MemoryStream(File.ReadAllBytes(file)))
{
var decoder = BitmapDecoder.Create(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
var photo = decoder.Frames[0];
int width, height;
if (photo.Width > photo.Height)
{
width = ThumbnailSize;
height = (int)(photo.Height * ThumbnailSize / photo.Width);
}
else
{
width = (int)(photo.Width * ThumbnailSize / photo.Height);
height = ThumbnailSize;
}
var target = new TransformedBitmap(photo, new ScaleTransform(
width / photo.Width * 96 / photo.DpiX,
height / photo.Height * 96 / photo.DpiY,
0, 0));
var final = BitmapFrame.Create(target);
var encoder = new JpegBitmapEncoder { QualityLevel = 90 };
encoder.Frames.Add(final);
var d = Path.Combine(dest, Path.GetFileName(file));
using (var f = File.Create(d))
{
encoder.Save(f);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment