2

如何使用Windows.Web.Http在Windows應用商店應用程序下載並存儲來自互聯網的jpeg圖像?如何使用Windows.Web.Http下載和存儲圖像?

我面臨的問題是,我不知道什麼得到...異步和寫...異步方法我必須使用圖像?這與文件非常不同,而不是字符串。


只有Windows.Web.Http

沒有第三方解決方案

如果您有其他建議,請使用評論部分,而不是答案。謝謝!


…  
using Windows.Storage; 
using Windows.Web.Http; 

Uri uri = new Uri("http://image.tmdb.org/t/p/w300/" + posterPath); 
HttpClient httpClient = new HttpClient(); 

// I guess I need to use one of the Get...Async methods? 
var image = await httpClient.Get…Async(uri); 

StorageFolder localFolder = ApplicationData.Current.LocalFolder; 
StorageFolder cachedPostersFolder = await localFolder.CreateFolderAsync("cached posters", CreationCollisionOption.OpenIfExists); 

StorageFile posterFile = await cachedPostersFolder.CreateFileAsync(posterPath, CreationCollisionOption.ReplaceExisting); 

// I guess I need to use one of the Write...Async methods? 
await FileIO.Write…Async(posterFile, image); 
+0

爲什麼不使用[BackgroundDownloader(http://msdn.microsoft.com/library/windows相反,你可以使用GetStreamAsync的方式,我有/apps/windows.networking.backgroundtransfer.backgrounddownloader.aspx)? – 2014-11-02 23:32:00

回答

6

可以使用GetBufferAsync方法獲得一個緩衝區,然後調用FileIO.WriteBufferAsync到緩衝區寫入文件:

Uri uri = new Uri("http://i.stack.imgur.com/ZfLdV.png?s=128&g=1"); 
string fileName = "daniel2.png"; 

StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
     fileName, CreationCollisionOption.GenerateUniqueName); 


HttpClient client = new HttpClient(); 

var buffer = await client.GetBufferAsync(uri); 
await Windows.Storage.FileIO.WriteBufferAsync(destinationFile, buffer); 
1
image1.Source = new BitmapImage(new Uri("http://www.image.com/image.jpg",  UriKind.RelativeOrAbsolute)); 


     using (var mediaLibrary = new MediaLibrary()) 
     { 
      using (var stream = new MemoryStream()) 
      { 
       var fileName = string.Format("Gs{0}.jpg", Guid.NewGuid()); 
       bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100); 
       stream.Seek(0, SeekOrigin.Begin); 
       var picture = mediaLibrary.SavePicture(fileName, stream); 
       if (picture.Name.Contains(fileName)) return true; 
      } 
     } 
0

這是一個類似的答案約翰的,但是在WP8.1中,您不能使用GetBufferAsync。使用功能

Uri uri = new Uri(UriString); 
string fileName = p4.IconLocation; 

HttpClient client = new HttpClient(); 

var streamImage = await client.GetStreamAsync(uri); 

await SaveToLocalFolderAsync(streamImage, fileName); 

public async Task SaveToLocalFolderAsync(Stream file, string fileName) 
    { 
     StorageFolder localFolder = ApplicationData.Current.LocalFolder; 
     StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); 
     using (Stream outputStream = await storageFile.OpenStreamForWriteAsync()) 
     { 
      await file.CopyToAsync(outputStream); 
     } 
    } 
相關問題