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

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

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

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

谢谢!

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

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

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

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

WebClient类获取响应并将其存储在e.Result变量中。 如果仔细观察,e.Result的类型已经是Stream所以它可以传递给你的方法PicToIsoStore

有一个简单的方法

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

请尝试以下方法

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