开发者

Save a remote image in to Isolated Storage

开发者 https://www.devze.com 2023-03-03 01:32 出处:网络
I tried using this code for download image: void downloadImage(){ WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadString

I tried using this code for download image:

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

The problem is: how get the stream of image?

Thank!


It's easy to get a stream to a file in Isolated Storage. IsolatedStorageFile has an OpenFile method that gets one.

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


You need to put e.Result as a parameter when calling PicToIsoStore inside your client_DownloadStringCompleted method

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

The WebClient class gets response and stores it in the e.Result variable. If you look carefully, the type of e.Result is already Stream so it is ready to be passed to your method PicToIsoStore


There is an easy way

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


Try the following

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

Then you can use the following

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

精彩评论

暂无评论...
验证码 换一张
取 消