首页 文章

在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);

但是当时没有显示图片 .

Microsoft的文档仅包含通过从内部存储打开文件获得的流中图像加载的示例 . 但我需要加载图像,即保存在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:

    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 []并将其绑定到页面上的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);
    

    我不擅长异步编程,但我认为这样可行 .

相关问题