2

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[ ]?

Olga
  • 1,395
  • 2
  • 25
  • 34
  • 2
    Since WPF provides built-in type conversion from several source types (including `byte[]`) to `ImageSource`, you should be able to simply write ``. The byte array must contain an encoded image buffer, e.g. a PNG or JPEG. – Clemens Sep 07 '16 at 09:24
  • 1
    For the Binding to work, the DataContext of the Image control (or one of its parent controls or the MainWindow), must be set to an instance of a class that implements your IFile interface. – Clemens Sep 07 '16 at 09:42
  • Clemens, thanks! really works!! – Olga Sep 07 '16 at 09:45
  • 1
    As it was not an exact duplicate, I've reopened the question and added an answer. – Clemens Sep 07 '16 at 09:52

1 Answers1

8

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);
}
Clemens
  • 123,504
  • 12
  • 155
  • 268