C# BitmapFrame.Thumbnail property is null for some images

524 Views Asked by At

I am trying to modify this project for showing images in a directory. But the problem is that the code does not work for all images like this one. So the problem is

BitmapFrame bitmapFrame = BitmapFrame.Create(new Uri(path))

Here on the repository BitmapFrame.Thumbnail property is null for some images. I don't find anything about what's wrong with those images.

How to make it work for all images?

Working example Working example Not working example Not working example

2

There are 2 best solutions below

0
On

I ran into this same issue with the SDK example. Some jpg's are shown as a small white rectangle, instead of a thumbnail. Maybe this is the result of JPG's in an unsupported format, or JPG's not containing EXIF information in the header ? I am not sure.. I could solve it with the procedure Raviraj provided.

However, the answer Raviray provided is a bit short.. the thumbnail only works, when the result of the function is passed into the BitmapFrame constructor of your image class. The BitmapFrame class has a constructor with two arguments for that, the second one is the thumbnail bitmap, see How to override(use) BitmapFrame.Thumbnail property in WPF C#?

I got it working with "bad" jpg's, changing Photo.cs in the SDK example, as follows..

    private BitmapSource CreateBitmapSource(Uri path)
    {
        BitmapImage bmpImage = new BitmapImage();
        bmpImage.BeginInit();
        bmpImage.UriSource = path;
        bmpImage.EndInit();
        return bmpImage;
    }

    private BitmapSource CreateThumbnail(Uri path)
    {
        BitmapImage bmpImage = new BitmapImage();
        bmpImage.BeginInit();
        bmpImage.UriSource = path;
        bmpImage.DecodePixelWidth = 120;
        bmpImage.EndInit();
        return bmpImage;
    }

    // it has to be plugged in here,
    public Photo(string path)
    {
        Source = path;
        _source = new Uri(path);
        // replaced.. Image = BitmapFrame.Create(_source);
        // with this:
        Image = BitmapFrame.Create(CreateBitmapSource(_source),CreateThumbnail(_source));
        Metadata = new ExifMetadata(_source);
    }
1
On

You can use the following method for creating the thumbnails for images which don't have one.

private BitmapSource CreateThumbnail(string path)
{
    BitmapImage bmpImage = new BitmapImage();
    bmpImage.BeginInit();
    bmpImage.UriSource = new Uri(path);
    bmpImage.DecodePixelWidth = 120;
    // bmpImage.DecodePixelHeight = 120; // alternatively, but not both
    bmpImage.EndInit();
    return bmpImage;
}