图像解码(缩略图)和使用数据绑定



我正在下载一堆图像并通过数据绑定将它们显示在列表框中。即

...
<ListBox.ItemTemplate>
  <DataTemplate>
    <Image Source="{Binding ImageUrl}" Height="90" Width="90" Stretch="UniformToFill" />
  </DataTemplate>
</ListBox.ItemTemplate>
...

我想要图像的缩略图。尽管将图像控件设置为 90x90,但图像仍然以其完整的原始大小进行解码,因此它们占用的内存比应有的多得多。

有一个 PictureDecoder 类可用于此目的,但从外观上看,它不能在后台线程上使用。

我尝试创建一个使用ThreadPool和WriteableBitmap的附加依赖项属性:

public static readonly DependencyProperty DecodingSourceProperty = DependencyProperty.RegisterAttached(
DecodingSourcePropertyName,
typeof (Uri),
typeof (Image),
new PropertyMetadata(null, OnDecodingSourcePropertyChanged));
static void OnDecodingSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
    var img = d as Image;
    double height = img.Height;
    double width = img.Width;
    var uri = (Uri)e.NewValue;
    var bmp = new WriteableBitmap((int)width, (int)height);
    ThreadPool.QueueUserWorkItem(callback => {
        var web = new WebClient();
        web.OpenReadCompleted += (sender, evt) => {
            bmp.LoadJpeg(evt.Result);
            evt.Result.Dispose();
            Deployment.Current.Dispatcher.
            BeginInvoke(() = > {
                img.Source = bmp;
            });
        };
        web.OpenReadAsync(uri);
    }
    });
}
<Image helpers:ImageExt.DecodingSource="{Binding ImageUrl}" Height="90" Width="90" Stretch="UniformToFill" />

但它不尊重我设置的拉伸属性。

我想知道是否有任何第三方控件可以达到类似目的?

我想避免在服务器上调整图像大小 - 尽管这似乎是最简单的方法。

你不能

只用Image.GetThumbnailImage吗?

如果图像包含嵌入的缩略图图像,则此方法将检索嵌入的缩略图并将其缩放到请求的大小。如果图像不包含嵌入的缩略图图像,则此方法通过缩放主图像来创建缩略图图像。

Image.GetThumbnailImage Method

在Windows Phone 8中,BitmapImage 类中有新的属性 - DecodePixelWidth 和 DecodePixelHeight

<Image>
   <BitmapImage UriSource="{Binding Url"}  DecodePixelWidth="200" DecodePixelHeight="200" />
</Image>

它会将图像解码为指定的分辨率,从而减少内存使用量。(如果要保持纵横比,只需使用其中一个属性而不是两个属性)。

最新更新