Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

c# - Display image from byte[ ]

I use C#, wpf. I have an image, it is stored in the form of: byte[ ]

public interface IFile
{
    int Id { get; set; }
    byte[] FileData { get; set; }        
    string FileName { get; set; }
    int? FileSize { get; set; }
    string FileExtension { get; set; }
}

How can I display my image (FileData byte[ ]) on the form?

<GroupBox BorderThickness="1">
    <Image Source="..."/>
</GroupBox>

I have to write in Source="...", if I create a temporary file from a byte[ ]?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Provided that you have a view model class that implements your IFile interface, and that its FileData property contains an encoded image buffer like a PNG or JPEG, you could directly bind to the property like this:

<Image Source="{Binding FileData}"/>

This is because WPF provides built-in, automatic type conversion from several source types, including byte[], to ImageSource.


The type conversion is performed by the class ImageSourceConverter, which is registered as TypeConverter

[TypeConverterAttribute(typeof(ImageSourceConverter))]
public abstract class ImageSource ...

and does something similar to this:

byte[] buffer = ...
ImageSource result;
using (var stream = new MemoryStream(buffer))
{
    result = BitmapFrame.Create(
        stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...