问题
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