将远程图片保存到隔离存储中

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个回答

5
你需要在client_DownloadStringCompleted方法内调用PicToIsoStore方法时,将e.Result作为参数传递。
void client_DownloadStringCompleted(object sender,
     DownloadStringCompletedEventArgs e)
        {
           PicToIsoStore(e.Result);
        }

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

5

在隔离存储中将流写入文件很容易。使用IsolatedStorageFile类的OpenFile方法即可实现。

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

2

有一种简单的方法

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

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

在Silverlight中不可用System.Drawing.Image。 - D.Rosado

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接