Olga Olga - 1 year ago 120
C# Question

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="..."/>

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

Answer Source

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

public abstract class ImageSource ...

and does something similar to this:

byte[] buffer = ...
ImageSource result;
using (var stream = new MemeoryStream(buffer))
    result = BitmapFrame.Create(
        stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download