Domanda

Ho qualche problema a creare un BitmapImage da un MemoryStream da byte PNG e GIF ottenuti da una richiesta Web. I byte sembrano essere scaricati bene e il BitmapImage L'oggetto viene creato senza problemi, tuttavia l'immagine non sta effettivamente rendendo la mia interfaccia utente. Il problema si verifica solo quando l'immagine scaricata è di tipo PNG o GIF (funziona bene per JPEG).

Ecco il codice che dimostra il problema:

var webResponse = webRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream.CanRead)
{
    Byte[] buffer = new Byte[webResponse.ContentLength];
    stream.Read(buffer, 0, buffer.Length);

    var byteStream = new System.IO.MemoryStream(buffer);

    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.DecodePixelWidth = 30;
    bi.StreamSource = byteStream;
    bi.EndInit();

    byteStream.Close();
    stream.Close();

    return bi;
}

Per verificare che la richiesta Web ottenga correttamente i byte che ho provato quanto segue che salvano i byte su un file su disco e quindi carica l'immagine usando un UriSource piuttosto che a StreamSource E funziona per tutti i tipi di immagini:

var webResponse = webRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream.CanRead)
{
    Byte[] buffer = new Byte[webResponse.ContentLength];
    stream.Read(buffer, 0, buffer.Length);

    string fName = "c:\\" + ((Uri)value).Segments.Last();
    System.IO.File.WriteAllBytes(fName, buffer);

    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.DecodePixelWidth = 30;
    bi.UriSource = new Uri(fName);
    bi.EndInit();

    stream.Close();

    return bi;
}

Qualcuno ha qualche luce da brillare?

È stato utile?

Soluzione

Aggiungere bi.CacheOption = BitmapCacheOption.OnLoad direttamente dopo il tuo .BeginInit():

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
...

Senza questo, BitmapImage utilizza l'inizializzazione pigra per impostazione predefinita e lo stream sarà chiuso da allora. Nel primo esempio provi a leggere l'immagine eventualmente Collegata Memorystream chiuso o addirittura eliminato. Il secondo esempio utilizza il file, che è ancora disponibile. Inoltre, non scrivere

var byteStream = new System.IO.MemoryStream(buffer);

meglio

using (MemoryStream byteStream = new MemoryStream(buffer))
{
   ...
}

Altri suggerimenti

Sto usando questo codice:

public static BitmapImage GetBitmapImage(byte[] imageBytes)
{
   var bitmapImage = new BitmapImage();
   bitmapImage.BeginInit();
   bitmapImage.StreamSource = new MemoryStream(imageBytes);
   bitmapImage.EndInit();
   return bitmapImage;
}

Potrebbe essere che dovresti eliminare questa riga:

bi.DecodePixelWidth = 30;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top