FromByteArray example

Jul 30, 2015 at 6:47 AM
Hi all

I am creating a byte[] using ToByteArray (see ToByteArray Snippet), but when I try to reconstitute this into a WritableBitmap (see FromByteArray Snippet) I get an ArgumentException complaining about array out of bounds. I think the resize from 1,1 to the original image size is failing. But I am not sure what I am doing wrong. Any ideas?


FromByteArray Snippet

foreach (byte[] binary in Model.Client.Photos)
WriteableBitmap wbmp = BitmapFactory.New(1, 1).FromByteArray(binary);

ToByteArray Snippet

StorageFile file = await openPicker.PickSingleFileAsync();
        // If the file path and name is entered properly, and user has not tapped 'cancel'..
        if (file != null)
            var property = await file.Properties.GetImagePropertiesAsync();

            WriteableBitmap wb = new WriteableBitmap((int)property.Width, (int)property.Height);

            using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                await wb.SetSourceAsync(fileStream);
                byte[] binaryImage = wb.ToByteArray();
Jul 30, 2015 at 7:59 AM
You need to keep track of the original width and height of the byte array image data as well and initialize the WriteableBitmap with that. Otherwise the WB won't know just from the byteArray.Length what the dimension of the WB is!

WriteableBitmap wbmp = BitmapFactory.New(widht, height).FromByteArray(binary);
  • Rene