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

只愿长相守 提交于 2019-11-30 06:53:09

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;
        }
shima

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;
    }
}

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;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!