Sunday, August 22, 2010

WPF - Saving Application Memory by Specifying Decoded Size for Images

We use images alot in our WPF applications. It is nearly always the case that we have to show the image in different size than it was originally created. To do that, we specify Width and Height for <Image>. WPF caches the image. It is interesting to note that it is not cached as displayed. It is cached as its original size. So if we have a 800 X 600 image which we are just showing as thumbnail size of 50 X 50 by specifying the Height and Width of <Image>, we are caching it as 800 X 600. Now assume we have 100s of these images throughout the application. This would be a big loss for the application memory if we don't specify the Decoded Size explicitly.

In this post, we will be using the same image as used in the previous post. The image is as follows:

Let us instantiate this as a BitmapImage in the Resources section of Window.

<Window x:Class="WPFComboBoxEditable.WindowImageDecodedSize"
Title="WindowImageDecodedSize" >
<BitmapImage UriSource="C:\Chundrigar.jpg" x:Key="image1"
DecodePixelWidth="200" DecodePixelHeight="150" />
<Image Source="{StaticResource image1}" Height="200" Width="150" />

As you can see that we have specified the DecodePixelWidth and DecodePixelHeight for BitmapImage. This would cache the image as the size specified. Since we are showing the image in the same size in <Image>, it would be shown as follows:

This would definitely save a lot in terms of memory usage of the application.

No comments: