During a recent WPF session I needed to build a ListBox that showed a bunch of images loaded from an arbitrary directory. Thanks to WPF's data binding, this was trivial - I just needed to get a collection of objects that each had a property pointing to the full path of the image, and WPF would take care of all the loading/displaying. Something like this:
The assumption here is that the DataContext for this window is set to a collection of "Photo" objects. The Photo class has a member called "FullPath" which is just a string with the full path of the photo on disk - this is what the Image.Source member expects.
This worked, but it didn't take long to see a major issue: With today's cameras, loading multiple 5+ megapixel images could take a while (not to mention the RAM requirements).
After a little digging, I found a solution. There exists a feature in the BitmapImage class that allows you to load an image but tell it to only load a thumbnail. To use this, you have to step out of the shrink-wrapped data binding world and insert a converter into the equation. Basically, this converter will take the above string with the full image path, it will load the image (as a thumbnail), and pass it back into the Image.Source parameter as a BitmapImage, which it's happy to consume.
First, let's look at this converter's code and how it loads the thumbnail:
Notice line #7. That's the magic line which tells it how big of a thumbnail to load. The smaller the number, the quicker the load, the lower the quality. Notice also line #8 - this is there to force the image file to be closed after it's loaded. Without that, I found that my app couldn't write back to the image file since the ListBox still had it open.
Next, let's look at the XAML change to insert this converter into the mix. You'll need to create a resource for it:
The "local:" namespace directive on line #2 is one I'd made sure to add to my main "Window" declaration, like this (line #4):
Lastly, use this new resource in the Image element so that FullPath (a string) gets pushed through the converter before Image.Source gets it:
That's it. Your images will now load very quickly. Tweak the thumbnail size to vary the speed versus quality.