在Windows Phone 8.1中,如何从字节数组(数据库)中加载、显示、转换图像?

7
完整问题是如何在Windows Phone 8.1中显示从数据库加载的图像。 图像数据已作为字节数组加载(已检查 - 加载正常)。
通过指定urisource来显示图像可以正常工作。
Image img = new Image();
img.Source = new BitmapImage() {UriSource = new Uri("http://www.example.com/1.jpg") };
rootgrid.Children.Add(img);    

但是当字节数组(图像)转换为BitmapImage时,什么也不会显示。

到目前为止,我找到的唯一没有异常的示例是:

public BitmapImage ConvertToBitmapImage(byte[] image)
{
    InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
    var bitmapImage = new BitmapImage();
    var memoryStream = new MemoryStream(image);
    memoryStream.CopyToAsync(ras.AsStreamForWrite());
    bitmapImage.SetSourceAsync(ras);
    return bitmapImage;
}

Image img = new Image();
img.Source = ConvertToBitmapImage(picturebytearray);
rootgrid.Children.Add(img);

但是没有显示图片。

微软的文档只包含从内部存储打开文件获得的流加载图像的示例。但我需要加载保存在sqlite数据库中的图像。图像数据以jpeg格式存储。

编辑: 基于freshbm的解决方案的工作代码:

public async Task<BitmapImage> ConvertToBitmapImage(byte[] image)
{
    BitmapImage bitmapimage = null;
    using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
    {
        using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
        {
            writer.WriteBytes((byte[])image);
            await writer.StoreAsync();
        }
        bitmapimage = new BitmapImage();
        bitmapimage.SetSource(ms);
    }
    return bitmapimage;
}

那么在构造函数中,可以使用以下代码:

img.Source = ConvertToBitmapImage(imagebytearray).Result;

否则
img.Source = await ConvertToBitmapImage(imagebytearray);
1个回答

8
你可以尝试这样将byte[]转换为BitmapImage:
你可以尝试以下代码来将byte[]转换为BitmapImage:
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{              
    using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
    {
       writer.WriteBytes((byte[])fileBytes);
       writer.StoreAsync().GetResults();
    }
    var image = new BitmapImage();
    image.SetSource(ms);
}

我在这里找到了它: http://www.codeproject.com/Tips/804423/Conversion-between-File-Byte-Stream-BitmapImage-an

我正在使用它从sqlite数据库读取byte[],并将其绑定到Page上的Image。

对于你的代码,请尝试为异步函数添加await:

public async Task<BitmapImage> ConvertToBitmapImage(byte[] image)
{
    InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
    var bitmapImage = new BitmapImage();
    var memoryStream = new MemoryStream(image);
    await memoryStream.CopyToAsync(ras.AsStreamForWrite());
    await bitmapImage.SetSourceAsync(ras);
    return bitmapImage;
}

Image img = new Image();
img.Source = await ConvertToBitmapImage(picturebytearray);
rootgrid.Children.Add(img);

我不擅长异步编程,但我认为这个代码会运行。


你的解决方案有效。但不是因为它是异步的(将我的更改为异步也没有帮助)。我在类构造函数中使用它,其中不允许使用“await”。 - Artur Alexeev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接