EasyText, EasyLicense 的作者, https://github.com/EasyHelper Good Good Study,Day Day Up.

 

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);

 

因为bitmapStreamSource比较大,造成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来生成图片了。

 

 

最后说一句:虽然解决了这个问题,不过每次都要下载高清图片,生成缩略图,这是很耗时的,所以在上传图片的时候就应该生成缩略图了,将缩略图保存起来了。因为在局域网中,网速比较快,这种方式基本也可以满足要求了。

 

posted @ 2011-12-02 06:36  LoveJenny  阅读(4310)  评论(3编辑  收藏  举报
EasyText, EasyLicense 的作者, https://github.com/EasyHelper Good Good Study,Day Day Up.