0

I have this ValueConverter to convert a byte[] into a BitmapImage:

  public class ByteArrayToImageConverter : IValueConverter
  {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var bitmapImage = new BitmapImage();
            var buffer = (byte[])value;
            var str = new MemoryStream(buffer).AsRandomAccessStream();
            bitmapImage.SetSource(str);
            return bitmapImage;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
  }

Strangely enough, when I run the code, the application hangs (deadlocks) in the in the line with SetSource.

Why is this happening? Am I doing something wrong?

halfer
  • 19,824
  • 17
  • 99
  • 186
SuperJMN
  • 13,110
  • 16
  • 86
  • 185

1 Answers1

0

I try use the code below that can convert.

var bytes = (byte[])value;

var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();

// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);

// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
return output;
lindexi
  • 4,182
  • 3
  • 19
  • 65
  • How would you call this in the Convert method, which you can't declare async? Besides that, creating a WriteableBitmap instead of a BitmapImage doesn't seem to make any sense. Or do you have an explanation? – Clemens Nov 09 '17 at 18:43
  • @Clemens I just want to tall you another answer for you duplicate question. – lindexi Nov 10 '17 at 01:16
  • Why "my duplicate question"? I neither asked nor closed the question. Makes no sense, sorry. Besides that the answer is useless in the context of the question. – Clemens Nov 10 '17 at 06:46
  • @Clemens For this duplicate question. I found the other question have no one who have this way. – lindexi Nov 10 '17 at 11:45
  • Then you should certainly answer the other question, not this one. But also the other question is clearly about SetSource. Calling SetSourceAsync is not option, here or there. – Clemens Nov 10 '17 at 11:47
  • @Clemens Dont you know some way to change the asynchronization to synchronization? – lindexi Nov 10 '17 at 12:30