I've got an image in PNG fo开发者_JAVA百科rmat in a StreamReader object. I want to display it on my WPF form. What's the easiest way to do that?
I've put an Image
control on the form, but I don't know how to set it.
The Image.Source
property requires that you supply a BitmapSource
instance. To create this from a PNG you will need to decode it. See the related question here:
WPF BitmapSource ImageSource
BitmapSource source = null;
PngBitmapDecoder decoder;
using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
{
decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
if (decoder.Frames != null && decoder.Frames.Count > 0)
source = decoder.Frames[0];
}
return source;
This seems to work:
image1.Source = BitmapFrame.Create(myStreamReader.BaseStream);
Instead of using a StreamReader, I would directly generate the Stream,
FileStream strm = new FileStream("myImage.png", FileMode.Open);
PngBitmapDecoder decoder = new PngBitmapDecoder(strm,
BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
myImage.Source = decoder.Frames[0];
where myImage is the name of your Image in XAML
<Image x:Name="myImage"/>
Update: If you have to use the StreamReader, you get the Stream by using .BaseStream.
精彩评论