如何将字节数组转换为 Windows 8.0 商店应用程序的 ImageSource [英] How to Convert byte array to ImageSource for Windows 8.0 store application

查看:22
本文介绍了如何将字节数组转换为 Windows 8.0 商店应用程序的 ImageSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 Windows 8 商店应用程序.我是新手.

I am working on Windows 8 store application. I am new at it.

我正在接收一个字节数组(字节 [])形式的图像.

I am receiving an image in the form of byte array (byte []).

我必须将其转换回 Image 并在 Image Control 中显示.

I have to convert this back to Image and display it in Image Control.

到目前为止,我在屏幕上有按钮和图像控件.当我点击按钮时,我调用以下函数

so far I have button and Image control on Screen. When I click button, I call following function

private async Task LoadImageAsync()
{
    byte[] code = //call to third party API for byte array
    System.IO.MemoryStream ms = new MemoryStream(code);
    var bitmapImg = new Windows.UI.Xaml.Media.Imaging.BitmapImage();

    Windows.Storage.Streams.InMemoryRandomAccessStream imras = new Windows.Storage.Streams.InMemoryRandomAccessStream();

    Windows.Storage.Streams.DataWriter write = new Windows.Storage.Streams.DataWriter(imras.GetOutputStreamAt(0));
    write.WriteBytes(code);
    await write.StoreAsync();
    bitmapImg.SetSourceAsync(imras);
    pictureBox1.Source = bitmapImg;
}

这不能正常工作.任何的想法?当我调试时,我可以看到以毫秒为单位的字节数组.但它没有被转换为 bitmapImg.

This is not working properly. any idea? When I debug, I can see the byte array in ms. but it is not getting converted to bitmapImg.

推荐答案

我在 代码项目

public class ByteImageConverter
{
    public static ImageSource ByteToImage(byte[] imageData)
    {
        BitmapImage biImg = new BitmapImage();
        MemoryStream ms = new MemoryStream(imageData);
        biImg.BeginInit();
        biImg.StreamSource = ms;
        biImg.EndInit();

        ImageSource imgSrc = biImg as ImageSource;

        return imgSrc;
    }
}

此代码应该适合您.

这篇关于如何将字节数组转换为 Windows 8.0 商店应用程序的 ImageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆