将远程映像保存到隔离存储

时间:2011-05-03 13:35:38

标签: c# silverlight windows-phone-7

我尝试使用此代码下载图片:

void downloadImage(){
 WebClient client = new WebClient();
 client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
                client.DownloadStringAsync(new Uri("http://mysite/image.png"));

        }

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
           //how get stream of image?? 
           PicToIsoStore(stream)
        }

        private void PicToIsoStore(Stream pic)
        {
            using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                var bi = new BitmapImage();
                bi.SetSource(pic);
                var wb = new WriteableBitmap(bi);
                using (var isoFileStream = isoStore.CreateFile("somepic.jpg"))
                {
                    var width = wb.PixelWidth;
                    var height = wb.PixelHeight;
                    Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
                }
            }
        }

问题是:如何获取图像流?

感谢!

4 个答案:

答案 0 :(得分:5)

在隔离存储中获取文件流很容易。 IsolatedStorageFile有一个OpenFile方法可以获得一个。

using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (IsolatedStorageFileStream stream = store.OpenFile("somepic.jpg", FileMode.Open))
    {
        // do something with the stream
    }
}

答案 1 :(得分:5)

e.Result方法中调用PicToIsoStore时,您需要将client_DownloadStringCompleted作为参数

void client_DownloadStringCompleted(object sender,
     DownloadStringCompletedEventArgs e)
        {
           PicToIsoStore(e.Result);
        }

WebClient类获取响应并将其存储在e.Result变量中。如果仔细查看,e.Result的类型已经Stream,因此可以将其传递给您的方法PicToIsoStore

答案 2 :(得分:2)

有一种简单的方法

WebClient client = new WebClient();
client.OpenReadCompleted += (s, e) =>
{
    PicToIsoStore(e.Result);
};
client.OpenReadAsync(new Uri("http://mysite/image.png", UriKind.Absolute));

答案 3 :(得分:0)

尝试以下

public static Stream ToStream(this Image image, ImageFormat formaw) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream);
  stream.Position = 0;
  return stream;
}

然后您可以使用以下

var stream = myImage.ToStream(ImageFormat.Gif);