Created
November 20, 2012 01:23
-
-
Save goyuix/4115351 to your computer and use it in GitHub Desktop.
WPF Image Resize code for LINQPad
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
<Query Kind="Statements"> | |
<Reference><RuntimeDirectory>\System.Xaml.dll</Reference> | |
<Reference><RuntimeDirectory>\WPF\WindowsBase.dll</Reference> | |
<Reference><RuntimeDirectory>\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