Silverlight 4.0: How to convert byte[] to image?

2019-02-04 11:10发布

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?

3条回答
劳资没心,怎么记你
2楼-- · 2019-02-04 11:23

An other way:

    public static BitmapImage ConvertStreamToImage(Stream stream)
    {
        BitmapImage _resultImage = new BitmapImage();

        _resultImage.SetSource(stream);

        return _resultImage;
    }

which uses these name spaces: using System.IO; using System.Windows.Media.Imaging;

查看更多
SAY GOODBYE
3楼-- · 2019-02-04 11:28

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;
        }
查看更多
在下西门庆
4楼-- · 2019-02-04 11:35

this code can convert image to byte[]

BitmapImage imageSource = new BitmapImage();
Stream stream = openFileDialog1.File.OpenRead();
BinaryReader binaryReader = new BinaryReader(stream);
currentImageInBytes = new byte[0];

currentImageInBytes = binaryReader.ReadBytes((int)stream.Length);
stream.Position = 0;
imageSource.SetSource(stream);

and this code can convert byte[] to image

public void Base64ToImage(byte[] imageBytes)
{

    using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        BitmapImage im = new BitmapImage();
        im.SetSource(ms);
        img.Source = im;
    }
}
查看更多
登录 后发表回答