Creating Image Thumbs with TransformedBitmap and ScaleTransform

With WPF and the classes in the System.Windows.Media.Imaging namespace, creating thumbnails from source images has never been easier to do. The code fragment below illustrates how to create thumbnails from a source image using TransformedBitmap and ScaleTransform. You can use the same technique to apply other types of transforms to an image, such as rotations.

Let’s first define our method signature…

using System.Windows.Media;
using System.Windows.Media.Imaging;
void CreateThumbnail(string sourceImage, string outputImage, int width, int height)

The next thing to do is to get our source image into a BitmapSource…

BitmapSource imageSource = BitmapFrame.Create(new Uri(sourceImage));

The class that defines the transformation to be applied to the image is ScaleTransform. We need to create one of these and set the scaling factor to be applied to the width and height…

ScaleTransform st = new ScaleTransform();
st.ScaleX = (double)width / (double)imageSource.PixelWidth;
st.ScaleY = (double)height / (double)imageSource.PixelHeight;

With the transform defined, we need a TransformedBitmap to apply it to…

TransformedBitmap tb = new TransformedBitmap(imageSource, st);

The TransformedBitmap now contains the bitmap after the scaling transform has been applied. The only thing left to do now is write it to disk. In the process we’ll add some metadata just to show how that is done as well…

BitmapMetadata thumbMeta = new BitmapMetadata("jpg");
thumbMeta.Title = "thumbnail";
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
encoder.Frames.Add(BitmapFrame.Create(tb, null, thumbMeta, null));
using (FileStream stream = new FileStream(outputImage, FileMode.Create))

And that’s pretty much all there is to it. As I mentioned above you can use this exact same approach to apply any of the other transform classes in the System.Windows.Media namespace. These are all derived from System.Windows.Media.Transform, and in addition to ScaleTransform they include: RotateTransform, SkewTransform, TranslateTransform, and MatrixTransform.

Leave a Reply

Your email address will not be published. Required fields are marked *