WPF客戶端讀取高清圖片很卡,縮圖解決方案
在Ftp上傳上,有人上傳了高清圖片,每張圖片大約2M。
如果使用傳統的BitmapImage類,然後繫結 Source 屬性的方法,有些電腦在首次會比較卡,一張電腦10秒,4張大約會卡40秒。
所以我先非同步的下載圖片,得到downloadFileStream物件,然後繫結到BitmapImage類上。例如:
System.Windows.Controls.Image photo = new Image
{
Width = 100,
Height = 100,
Margin = new Thickness(2),
Stretch = Stretch.Uniform
};
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = downloadFileStream;
bitmap.EndInit();
photo.Source = bitmap;
ListBoxItem lbi = new ListBoxItem()
{
DataContext = pvo,
Content = photo
};
this.lbPhotoes.Items.Add(lbi);
因為bitmap的StreamSource比較大,造成lbi物件比較大,所以lbPhotoes.Items.Add 方法在添加了兩張圖片之後就會卡大約30秒的時間。
所以嘗試使用縮圖的方式來使BitmapImage的物件變小,在這裡採用縮圖是因為客戶端需要圖片大小大致是
(100,100)。
完整的程式碼如下:
System.Windows.Controls.Image photo = new Image
{
Width = 100,
Height = 100,
Margin = new Thickness(2),
Stretch = Stretch.Uniform
};
using (System.Drawing.Image drawingImage = System.Drawing.Image.FromStream(downloadFileStream))
{
using (System.Drawing.Image thumbImage =
drawingImage.GetThumbnailImage(100, 100, () => { return true; }, IntPtr.Zero))
{
MemoryStream ms = new MemoryStream();
thumbImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
BitmapFrame bf = BitmapFrame.Create(ms);
photo.Source = bf;
}
}
ListBoxItem lbi = new ListBoxItem()
{
DataContext = pvo,
Content = photo
};
this.lbPhotoes.Items.Add(lbi);
在這裡,要引用System.Drawing.dll.使用System.Drawing.Image 類的GetThumbnailImage 方法來獲取thumbImage,接著使用MemoryStream來儲存縮圖的stream,接著用縮圖的stream來生成圖片了。
沒那麼複雜,只要直接設定DecodeWidth即可
其實Thumbnail內部也是這樣實現的
最後說一句:雖然解決了這個問題,不過每次都要下載高清圖片,生成縮圖,這是很耗時的,所以在上傳圖片的時候就應該生成縮圖了,將縮圖儲存起來了。因為在區域網中,網速比較快,這種方式基本也可以滿足要求了。