How to Create FileStreame from byte[]?

一曲冷凌霜 提交于 2019-12-12 05:18:16

问题


I have a class like this:

class person
{
    public string Name{get;set;}
    public byte[] PersonImage{get;set;}
}

When I Load my Person From DataBase I want to show PersonImage in a Image control, so I want to create BitmapImage from my byte[]:

var bitmapImage = new BitmapImage();

bitmapImage.BeginInit();
var filestream = new MemoryStream(PersonImage);
bitmapImage.StreamSource = filestream;

bitmapImage.EndInit();// I have Exception in this line 

My Exception is:

No imaging component suitable to complete this operation was found.

--edite my Inner Exception is :

Inner Exception:Exception from HRESULT:0*88982F50


回答1:


assuming PersonImage is really a valid byte[] representing an image try

var bitmapImage = new BitmapImage();

bitmapImage.BeginInit();
var somestream = new MemoryStream(PersonImage);
somestream.Position = 0; // "rewind" stream to start...
bitmapImage.StreamSource = somestream;

bitmapImage.EndInit();



回答2:


Your image is probably not a supported format. Try the following method:

public BitmapImage GetBitmapImage(byte[] imageData)
{
    BitmapImage bitmapImage = new BitmapImage();

    using (MemoryStream imageStream = new MemoryStream(imageData))
    using (Image image = Image.FromStream(imageStream))
    using (MemoryStream convertedImageStream = new MemoryStream())
    {
        bitmapImage.BeginInit();

        image.Save(convertedImageStream, ImageFormat.Png);

        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSouce = convertedImageStream;

        bitMapImage.EndInit();
    }

    return bitmapImage;
}

Make sure you include the following using statements at the top of your file:

using System.Drawing;
using System.Drawing.Imaging;


来源:https://stackoverflow.com/questions/9724876/how-to-create-filestreame-from-byte

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