深入分析WPF用戶端讀取高清圖片卡以及縮圖的解決方案詳解

來源:互聯網
上載者:User

在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來產生圖片了。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.