如何从byte []创建FileStream?

时间:2012-03-15 17:19:55

标签: c# wpf filestream

我有一个这样的课程:

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

当我从DataBase加载我的人时我想在Image控件中显示PersonImage,所以我想从我的byte []创建BitmapImage:

var bitmapImage = new BitmapImage();

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

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

我的例外是:

  

没有找到适合完成此操作的成像组件。

- edite 我的内在例外是:

  

内部异常:来自HRESULT的异常:0 * 88982F50

2 个答案:

答案 0 :(得分:1)

假设PersonImage确实是代表图片的有效byte[],请尝试

var bitmapImage = new BitmapImage();

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

bitmapImage.EndInit();

答案 1 :(得分:0)

您的图片可能不是受支持的格式。请尝试以下方法:

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

确保在文件顶部包含以下using语句:

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