今日您是第次访问
设为主页
添加改藏
网站优化
 
了解WPF技术
Silverlight WPF/E教程
WPF应用程序教程
当前位置:网站主页->Silverlight教程->文章浏览

Silverlight读取ZIP压缩包中图片

日期:2008-5-14   作者:由灵  Version : 2.0

实例来自“天使坠”,由灵代写介绍之:
    Silverlight客户端支持压缩包文件的读取,但是封装的类库功能相对有些限制,这也使得我们程序更安全了。
    实例介绍:
    初始化函数中创建了WebClient类实例,使用了OpenReadAsync方法用异步下载test.zip压缩文件。这样下载完成后会调用OpenReadCompleted方法事件,其中有两个参数,object表示webClient类,而OpenReadCompletedEventArgs是当前异步结果。Error属性是加载中发生的异常,Cancelled指加载过程中是否取消,Result是当前下载的数据了。实例中使用Application.GetResourceStream获取了数据流,并且在用户自定义LoadImageFromPackage方法读取了资源数据流并返回了BitmapImage对象,并赋值给imgTest控件的Source属性加工示了图像。主要代码段如下:

        public Page()
        {
            InitializeComponent();
            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
            webClient.OpenReadAsync(new Uri("test.zip", UriKind.Relative));     
        }

        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if ((e.Error == null) && (e.Cancelled == false))
            {
                Stream zipResourceInfo = e.Result;
                StreamResourceInfo imageResourceInfo = Application.GetResourceStream(new StreamResourceInfo(e.Result, null), new Uri("lyb.jpg", UriKind.RelativeOrAbsolute));
                BitmapImage image = LoadImageFromZipPackage("lyb.jpg", zipResourceInfo);
                this.imgTest.Source = image;
            }

        }

        public BitmapImage LoadImageFromZipPackage(string relativeUriString, Stream zipPackageStream)
        {
            Uri uri = new Uri(relativeUriString, UriKind.Relative);
            StreamResourceInfo zipPackageSri = new StreamResourceInfo(zipPackageStream, null);
            StreamResourceInfo imageSri = Application.GetResourceStream(zipPackageSri, uri);

            BitmapImage bi = new BitmapImage();
            bi.SetSource(imageSri.Stream);

            return bi;
        }

        天使注,如果不使用压缩技术,可以直接创建BitmapImage赋给Source属性实现:

public partial class Page : UserControl
    {

        public Page()
        {    this.imgFirst.Source = this.GetImage("/image/1.jpg");
        }

        private BitmapImage GetImage(string imagePath)
        {
            return new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));
        }// 将传入的图版路径生成 Image对象

        private void imgFirst_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            BitmapImage image = this.imgFirst.Source as BitmapImage;
            this.imgSecond.Source = this.GetImage(image.UriSource.ToString());            
        }
     }