Windows Phone - 字节数组到BitmapImage转换器抛出异常

时间:2013-08-13 17:07:02

标签: c# windows-phone-8 windows-phone converter bitmapimage

我有一个字节数组到BitmapImage转换器,它工作正常。对于我的应用程序中的磁贴支持,我从图像创建一个磁贴(调整大小并裁剪它)并将其作为字节数组保存到我的数据库中。现在,如果我想用我的转换器显示这个磁贴,它会引发异常:

无法找到该组件。 (HRESULT异常:0x88982F50)

我创建磁贴的方法:

            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;

我的实体内瓷砖的属性:

    private byte[] _tile;

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

我的字节数组到BitmapImage转换器方法:

    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;
    }

我认为问题是字节数​​组在数据库中保存为Base64编码字符串,并且在解码回字节数组时出错,但我不知道如何解决它。

1 个答案:

答案 0 :(得分:2)

我很关心你创建字节数组的方法。您是否有某些原因未使用SaveJpeg扩展程序?我不认识你正在制作的WritableBitmap.ToByteArray电话。请尝试使用以下代码:

int quality = 90;

using (var ms = new System.IO.MemoryStream()) {
    bmp.SaveJpeg(ms, bmp.PixelWidth, bmp.PixelHeight, 0, quality);
    item.Tile = ms.ToArray();
}
相关问题