Magnus Ahlin
Magnus Ahlin

Reputation: 655

Loading image from bytes gives AG_E_NETWORK_ERROR

Im writing my own cache for for our Silverlight application to get around any size problems. The cache works fine, however, it doesnt work for images. Ive narrowed down the problem to a little test application that converts a BitmapImage to bytes (to simulate reading it our from the cache) and then convert those bytes back into an image.

Here is the code:

public MainPage()
{
    InitializeComponent();
    firstImage.ImageOpened += first_Loaded;
}

void first_Loaded(object sender, RoutedEventArgs e)
{
    var bmp = firstImage.Source;
    var bytes = ToByteArray(bmp as BitmapImage);
    otherImage.Source = CreateImageFromBytes(bytes);
}



private byte[] ToByteArray(BitmapImage bi)
{
    var enc = new BitmapEncoder(bi);
    return enc.GetBitmapData();
}

private BitmapImage CreateImageFromBytes(byte[] data)
{
    var bitmapImage = new BitmapImage();
    bitmapImage.ImageFailed += bitmapImage_ImageFailed;
    var ms = new MemoryStream(data);
    bitmapImage.SetSource(ms);
    return bitmapImage;
}

void bitmapImage_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
    Console.WriteLine(e.ErrorException.Message);
}

The ImageFailed event is always raised with the message "AG_E_NETWORK_ERROR" Ive read a little about the problem and it seems to have to do with the origin of the image being different but surely I should be able to load an image from bytes in memory right?

Any ideas how to get around this?

I should add that the converting to bytes works fine since if I save those bytes down to disk I can open the image.

Upvotes: 1

Views: 251

Answers (1)

Clemens
Clemens

Reputation: 128061

From the Remarks in the Silverlight BitmapImage page on MSDN:

The BitmapImage can be used to reference images in the JPEG and PNG file formats.

Unfortunately the BitmapEncoder class that you are using seems to encode bitmaps in BMP format. Hence the encoded buffer can't be decoded by BitmapImage.

You would have to find another implementation of a BitmapEncoder, which is capable of encoding JPEG or PNG.

Upvotes: 2

Related Questions