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

标签 c# windows-phone-8 windows-phone converters bitmapimage

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

找不到组件。 (HRESULT 异常:0x88982F50)

我创建图 block 的方法:

            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;

我的实体中图 block 的属性:

    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 编码字符串,并且在解码回字节数组时出现错误,但我不知道如何解决它。

最佳答案

我担心您创建字节数组的方法。您不使用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();
}

关于c# - Windows Phone - 字节数组到 BitmapImage 转换器抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18215157/

相关文章:

windows-phone-8 - 如何更改外部矩形的不透明度?

c# - 如何在 Windows Phone 上更改 C# 中的本地化?

c# - 在 AppResources 中使用字符串

c# - 尝试使用 JustMock 对事件进行单元测试

javascript - 如何在jQuery函数执行时显示加载进度条?

c# - 从 ListBox 中的单击项获取数据

windows-phone - microsoft.phone.userdata.contact.id

c# - 将 bool 值绑定(bind)到控件的可见性时如何防止闪烁

c# - .NET Native 代码在构造函数上崩溃?.Invoke()(空传播)

c# - 无法添加实体类型 'X' 的种子实体,因为没有为所需属性 "..ID"提供值