Set Silverlight Image Source from byte array

7

Posted by Joe | Posted in Silverlight | Posted on 03-06-2009

I’ve been playing around with Silverlight and WCF services and I came across the need to set the Source of an Image control in Silverlight from a byte array. I have a service method which returns an image from the server as a byte array which I want to show in the Silverlight application.

My service method is simple and looks like this:

using System.IO;

public byte[] GetImage(string serverPath)
{
    return File.ReadAllBytes(serverPath);
}

In the Silverlight application I create a MemoryStream from the byte array, then a BitmapImage from the MemoryStream and set the image source to the BitmapImage.


using System.IO;
using System.Windows.Media.Imaging;

void proxy_GetImageCompleted(object sender, GetImageCompletedEventArgs e)
{
    MemoryStream stream = new MemoryStream(e.Result);
    BitmapImage b = new BitmapImage();
    b.SetSource(stream);
    imgImage.Source = b;
}

proxy_GetImageCompleted is the event handler for when my asynchronous call to GetImage completes, where e.Result is the byte array.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit

Comments (7)

How to convert BitmapImage to byte array ?
Thank you

Hi Marc

In Silverlight 2 there is no way to the get a byte array from the BitmapImage.

In what situation do you need to do this?

Cheers
Joe

Maybe it’s not necessary. I was just asking to find a solution for resizing the BitmapImage because I need to use it immediatly after the user has selected it from his Hard Drive since the image can be huge and I don’t want to validate a small image. I want people to send any image size since a lot of people do not know how to do it I want my program to do it for them. But I saw no way else then resizing the image on my WCF service AFTER I sent it asynchronously. But the user have his image on hand very huge and the application becomes very slow if the user upload many images like this. So I really need to resize the image at the source between the user selecting it in his hard drive and showing it to him in the canvas.

Marc

You can resize the image at the client using FJCore.

See the following post for details:
http://www.joe-stevens.com/2009/06/22/resize-image-with-silverlight-and-fjcore-before-uploading-to-server/

Cheers
Joe

Great post! It was most useful to me. Thanks.

Vivek

Not done VB.NET for a while but can’t spot anything in the code. It looks like you may be using WPF here? At what point when debugging do you get the error?

Cheers
Joe

Can you post the entire code ?
I ‘m new in Silverlight and I need some help…
Thank you

Write a comment