5

Ho aggiunto Windows.UI.Xaml.Controls.Image su una tela. Sto usando HttpClient per effettuare chiamate http per scaricare l'immagine. Sto ottenendo l'immagine come stream e aggiungendo come sorgente di un oggetto BitmapImage, ma l'immagine non è caricata. Qualcuno può dirmi che cosa sto facendo male CodiceC# Metro app Come caricare l'immagine dal web

:

 var httpClient = new HttpClient(); 
     var content = await httpClient.GetStreamAsync(imageUrl); 


      var ras = new InMemoryRandomAccessStream(); 
      await content.CopyToAsync(ras.AsStreamForWrite()); 
      bitmap = new BitmapImage(); 
      bitmap.SetSource(ras); 

      myImage.Source = bitmap; 
+1

Nel desktop Silverlight, è possibile semplicemente rendere la fonte dell'immagine l'URL desiderato, e gestirà tutto per voi. Puoi fare lo stesso qui? –

risposta

10

Sono riuscito a farlo funzionare. Sotto è il codice:

 var httpClient = new HttpClient();    
    var contentBytes = await httpClient.GetByteArrayAsync(uri);       
    var ims = new InMemoryRandomAccessStream();     
    var dataWriter = new DataWriter(ims); 
    dataWriter.WriteBytes(contentBytes); 
    await dataWriter.StoreAsync(); 
    ims.Seek(0); 

    bitmap = new BitmapImage();     
    bitmap.SetSource(ims);     

    myImage.Source = bitmap;     
+2

Questa è probabilmente la cosa migliore su internet. Mi sono quasi arreso e ho scaricato il file nell'archivio locale, che non è quello che volevo fare. Grazie mille! – jbkkd

+1

Ancora utile per tre anni! Grazie saikamesh; _assoluto un problema di una settimana per me._ – iSofia

5

Credo che questo funzionerà:

myImage.Source = new BitmapImage(new Uri(imageUrl)); 
2

Ecco un frammento di codice che ho usato per scaricare correttamente le immagini dal web. Copia l'immagine nella memoria locale e restituisce un URI nella nuova posizione (locale).

 using (var response = await HttpWebRequest.CreateHttp(internetUri).GetResponseAsync()) 
     { 
      using (var stream = response.GetResponseStream()) 
      { 
       var desiredName = string.Format("{0}.jpg", uniqueName); 
       var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceExisting); 

       using (var filestream = await file.OpenStreamForWriteAsync()) 
       { 
        await stream.CopyToAsync(filestream); 
        return new Uri(string.Format("ms-appdata:///local/{0}.jpg", uniqueName), UriKind.Absolute); 
       } 
      } 
     } 
1

è possibile farlo utilizzando XAML:

Il sistema operativo sarà fare un po 'di caching, ma questo non garantisce che ogni volta che è necessario l'immagine sarà nella cache. Avrai bisogno di salvarlo nella memoria locale se lo desideri.

Problemi correlati