Windows Phone - byte array to BitmapImage converter throws exception

2

I have a byte array to a BitmapImage converter and it works fine. For tile support within my app, I create a tile from an image (resize and crop it) and save it into my database as byte array. Now, if I want to display this tile with my converter, it throws an exception:

The component cannot be found. (Exception from HRESULT: 0x88982F50)

My method for creating the tile:

            WriteableBitmap bmp = new WriteableBitmap(img);

            int height = bmp.PixelHeight;
            int newHeight = 0;

            int width = bmp.PixelWidth;
            int newWidth = 0;

            // calculate new height and new width...

            bmp = bmp.Resize(newWidth, newHeight, WriteableBitmapExtensions.Interpolation.Bilinear);
            bmp = bmp.Crop(0, 0, 336, 336);
            byte[] byteArray = bmp.ToByteArray();

            item.Tile = byteArray;

My property for the tile within my entity:

    private byte[] _tile;

    [Column(DbType = "IMAGE")]
    public byte[] Tile
    {
        get { return _tile; }
        set { SetProperty(ref _tile, value); }
    }

My byte array to BitmapImage converter method:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value is byte[])
        {
            using (var stream = new MemoryStream((byte[])value))
            {
                stream.Seek(0, SeekOrigin.Begin);

                BitmapImage image = new BitmapImage();
                image.SetSource(stream);

                return image;
            }
        }

        return null;
    }

I think the problem is that the byte array is saved as Base64 encoded string in the database and there's an error while decoding back to byte array, but I don't know how to solve it.

c#
windows-phone-8
windows-phone
converter
bitmapimage
asked on Stack Overflow Aug 13, 2013 by zrkl • edited Jun 28, 2016 by Neil Turner

1 Answer

2

I'm concerned about your methodology for creating a byte array. Is there some reason you're not using the SaveJpeg extension? I don't recognize the WritableBitmap.ToByteArray call you're making. Try instead the following code:

int quality = 90;

using (var ms = new System.IO.MemoryStream()) {
    bmp.SaveJpeg(ms, bmp.PixelWidth, bmp.PixelHeight, 0, quality);
    item.Tile = ms.ToArray();
}
answered on Stack Overflow Aug 18, 2013 by lsuarez

User contributions licensed under CC BY-SA 3.0