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

时间:2012-09-22 16:06:08

标签: silverlight windows-phone-7

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

...
<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" />

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

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

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

2 个答案:

答案 0 :(得分:0)

你能不能只使用Image.GetThumbnailImage

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

Image.GetThumbnailImage Method

答案 1 :(得分:0)

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

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

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

相关问题