Question

My application shows a large number of image thumbnails at once. Currently, I am keeping all full size images in memory, and simply scaling the image in the UI to create the thumbnail. However, I'd rather just keep small thumbnails in memory, and only load the fullsize images when necessary.

I thought this would be easy enough, but the thumbnails I'm generating are terribly blurry compared to just scaling the fullsize image in the UI.

The images are byte arrays with no header information. I know the size and format ahead of time, so I can use BitmapSource.Create to create an ImageSource.

 //This image source, when bound to the UI and scaled down creates a nice looking thumbnail
 var imageSource = BitmapSource.Create(
     imageWidth,
     imageHeight,
     dpiXDirection,
     dpiYDirection,
     format,
     palette,
     byteArray,
     stride);

using (var ms = new MemoryStream())
{
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(imageSource);
    encoder.Save(ms);

    var bi = new BitmapImage();
    bi.BeginInit();
    bi.CacheOption = BitmapCacheOption.OnLoad;

    //I can't just create a MemoryStream from the original byte array because there is no header info and it doesn't know how to decode the image!
    bi.StreamSource = ms;
    bi.DecodePixelWidth = 60;
    bi.EndInit();

    //This thumbnail is blurry!!!
    Thumbnail = bi;
}

I'm guessing its blurry since I'm converting it to png first, but when I use the BmpBitmapEncoder I get that "No imaging component available" error. In this case my image is Gray8, but I'm not sure why the PngEncoder can figure it out but the BmpEncoder can't.

Surely there must be someway to create a thumbnail from the original ImageSource without having to encode it to a bitmap format first? I wish BitmapSource.Create just let you specify a decode width/height like the BitmapImage class does.

EDIT

The final answer is to use a TransformBitmap with a WriteableBitmap to create the thumbnail and eliminate the original, full-size image.

var imageSource = BitmapSource.Create(...raw bytes and stuff...);
var width = 100d;
var scale = width / imageSource.PixelWidth;
WriteableBitmap writable = new WriteableBitmap(new TransformedBitmap(imageSource, new ScaleTransform(scale, scale)));
writable.Freeze();

Thumbnail = writable;
Was it helpful?

Solution

You should be able to create a TransformedBitmap from the original one:

var bitmap = BitmapSource.Create(...);
var width = 60d;
var scale = width / bitmap.PixelWidth;
var transform = new ScaleTransform(scale, scale);
var thumbnail = new TransformedBitmap(bitmap, transform);

In order to get ultimately rid of the original bitmap, you could create a WriteableBitmap from the TransformedBitmap:

var thumbnail = new WriteableBitmap(new TransformedBitmap(bitmap, transform));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top