Windows Phone-字节数组到BitmapImage转换器引发异常 [英] Windows Phone - byte array to BitmapImage converter throws exception
问题描述
我有一个BitmapImage转换器的字节数组,它工作正常。为了在我的应用程序中支持图块,我从图像创建了图块(调整大小和裁剪)并将其作为字节数组保存到我的数据库中。现在,如果要在转换器中显示此图块,则会引发异常:
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:
找不到组件。 (来自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;
我在实体中的图块的财产:
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); }
}
我的字节数组到BitmapImage转换器方法:
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;
}
我认为问题在于字节数组被保存为Base64编码的字符串数据库,解码回字节数组时出现错误,但是我不知道如何解决。
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.
推荐答案
I我担心您创建字节数组的方法。是否由于某些原因您不使用 SaveJpeg 扩展名?我无法识别您正在执行的WritableBitmap.ToByteArray调用。请改用以下代码:
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();
}
这篇关于Windows Phone-字节数组到BitmapImage转换器引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!