在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來產生圖片了。
最後說一句:雖然解決了這個問題,不過每次都要下載高清圖片,產生縮圖,這是很耗時的,所以在上傳圖片的時候就應該產生縮圖了,將縮圖儲存起來了。因為在區域網路中,網速比較快,這種方式基本也可以滿足要求了。