views:

1728

answers:

1
public Image Base64ToImage(string base64String)
    {
        // Convert Base64 String to byte[]
        byte[] imageBytes = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(imageBytes, 0,
          imageBytes.Length);

        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
        return image;
    }

I want to convert byte[] to image, however System.Drawing.Image is not supported in Silverlight. Any alternative?

+2  A: 

You need to create an ImageSource and assign that to an Image control or use an ImageBrush to set on the background. BitmapImage is located in the System.Windows.Media.Imaging namespace.

        byte[] imageBytes = Convert.FromBase64String(base64String);
        using (MemoryStream ms = new MemoryStream(imageBytes, 0,
          imageBytes.Length))
        {
            BitmapImage im = new BitmapImage();
            im.SetSource(ms);
            this.imageControl.Source = im;
        }

or for the ImageBrush

        byte[] imageBytes = Convert.FromBase64String(base64String);
        using (MemoryStream ms = new MemoryStream(imageBytes, 0,
          imageBytes.Length))
        {
            BitmapImage im = new BitmapImage();
            im.SetSource(ms);
            imageBrush.ImageSource = im;
            this.BoxBorder.Background = imageBrush;
        }
nyxtom
Why do you need to write the imageBytes to MemoryStream using the Write method? Aren't they put in from the ctor? Shouldn't im.SetSource(stream) be im.SetSource(ms)?
DaveB
Oh yea, I just reused the original code that he had above for convenience, but now looking at it - it is a bit off.
nyxtom