2011-05-03 88 views
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); 
       } 
      } 
     } 

的问题是:如何让图像的流?

谢谢!

回答

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

'System.Drawing.Image'不可用在Silverlight中 – 2013-02-13 14:33:40

5

可以很容易地得到一个流在独立存储中的文件。 IsolatedStorageFile有一个OpenFile方法得到一个。

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

你打电话PicToIsoStoreclient_DownloadStringCompleted方法

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

WebClient类得到响应,并将其存储在e.Result变量中,当需要把e.Result作为参数。如果你仔细看,e.Result的类型已经Stream,使其准备好要传递给你的方法PicToIsoStore

2

有一个简单的方法

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