2013-05-31 110 views
2

我想开发一个简单的Windows 8 Metro应用程序,它只需从给定的URL下载图像文件(说http://sample.com/foo.jpg),然后将其保存到图片库。通过Windows 8下载并保存图片库中的图像Metro XAML App

我在UI中有一个图像控件来显示下载的图像。 我也遇到了困难,将图像控件的图像源设置为新下载的图像(实际上我甚至无法下载它)。

另外,是否有可能将图像文件存储在图片库中的特定文件夹中(如果它不存在,那么应用程序应该创建它)?

我真的被困在这里。

请帮帮我。

回答

9

下面是一些粗略的代码,我相信它会完成你想要的。它假定您有两个图像控件(Image1和Image2),并且您已在清单中检查了图片库功能。看看XAML images sample以及

 Uri uri = new Uri("http://www.picsimages.net/photo/lebron-james/lebron-james_1312647633.jpg"); 
     var fileName = Guid.NewGuid().ToString() + ".jpg"; 

     // download pic 
     var bitmapImage = new BitmapImage(); 
     var httpClient = new HttpClient(); 
     var httpResponse = await httpClient.GetAsync(uri); 
     byte[] b = await httpResponse.Content.ReadAsByteArrayAsync(); 

     // create a new in memory stream and datawriter 
     using (var stream = new InMemoryRandomAccessStream()) 
     { 
      using (DataWriter dw = new DataWriter(stream)) 
      { 
       // write the raw bytes and store 
       dw.WriteBytes(b); 
       await dw.StoreAsync(); 

       // set the image source 
       stream.Seek(0); 
       bitmapImage.SetSource(stream); 

       // set image in first control 
       Image1.Source = bitmapImage; 

       // write to pictures library 
       var storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
        fileName, 
        CreationCollisionOption.ReplaceExisting); 

       using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) 
       { 
        await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0)); 
       } 
      } 
     } 

     // read from pictures library 
     var pictureFile = await KnownFolders.PicturesLibrary.GetFileAsync(fileName); 
     using (var pictureStream = await pictureFile.OpenAsync(FileAccessMode.Read)) 
     { 
      bitmapImage.SetSource(pictureStream); 
     } 
     Image2.Source = bitmapImage; 
    } 
+0

非常感谢! 这正是我所期待的。 :-) –

+0

如何在Win 8 Javascript应用程序上实现相同的操作? – Vikas

相关问题