0

I have a fixeddocument in which i have an image. The source-property of the image is bound to a byte-array (read from the database) in the datacontext of the document. When I am moving the mouse over the image I get a filenotfoundexception.

It looks like the documentviewer tries to load additional information about the rendered image from a file named "image" in the working directory which of course does not exist.

Does somebody know how to disable this behavior?

rjdkolb
  • 8,217
  • 8
  • 57
  • 77
Hurby
  • 74
  • 1
  • 6
  • We need more info about your issue, most importantly how you assign the image to the control. I generally use a converter and transform byte array to a bitmap and return that for an image control. – XAMlMAX Sep 15 '17 at 12:53
  • currently the source-property of the image is bound directly to the byte-array: public byte[] PassPhoto { get { return this.person.PassPhoto; } } i will try your solution... – Hurby Sep 15 '17 at 13:04
  • Try using a converter and transform that byte array to a bitmap. [more info here](https://stackoverflow.com/a/21555447/2029607) – XAMlMAX Sep 15 '17 at 13:05
  • 1
    converting the byte-array into a bitmap did not work (image was not shown) but converting to a ImageSource did it. thank you for pointing me in the right direction – Hurby Sep 15 '17 at 14:01
  • Did you set the cache option to `OnLoad` for the bitmap? Like [this post shows](https://stackoverflow.com/a/14337202/2029607). – XAMlMAX Sep 15 '17 at 14:03
  • no i did not. if i do it works like a charme too – Hurby Sep 18 '17 at 06:44
  • @XAMlMAX Why write an answer when you already link to a duplicate question in a comment? – Clemens Sep 28 '17 at 12:47
  • @Hurby Which version of WPF are you using? There should be built-in automatic type conversion from `byte[]` to `ImageSource`. – Clemens Sep 28 '17 at 12:49

1 Answers1

0

You can create a BitmapImage from a byte array with the following converter:

public class BytesToBitmapConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var bytes = (byte[])value; // make sure it is an array beforehand

        using (var ms = new System.IO.MemoryStream(bytes))
        {
            var image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.StreamSource = ms;
            image.EndInit();
            return image;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}  

Then in your xaml you would use this like so:

<Image Source="{Binding propertyNameHere, Converter={StaticResource converterName}}"/>
Clemens
  • 110,214
  • 10
  • 133
  • 230
XAMlMAX
  • 2,140
  • 1
  • 12
  • 21