如何将字节数组转换为 Windows 8.0 应用商店应用程序的映像源



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

我收到字节数组(字节 [])形式的图像。

我必须将其转换回图像并在图像控件中显示。

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

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;
}

这不能正常工作。知道吗?当我调试时,我可以看到以毫秒为单位的字节数组,但它没有转换为位图Img。

我在代码项目上找到了以下内容

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;
    }
}

此代码应该适合您。

你可以尝试这样的事情:

public object Convert(object value, Type targetType, object parameter, string language)
{
    byte[] rawImage = value as byte[];
    using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
    {
        using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
        {
            writer.WriteBytes((byte[])rawImage);
            // The GetResults here forces to wait until the operation completes
            // (i.e., it is executed synchronously), so this call can block the UI.
            writer.StoreAsync().GetResults();
        }
        BitmapImage image = new BitmapImage();
        image.SetSource(ms);
        return image;
    }
}

我在另一个线程中找到了以下答案(图像到字节[],转换和转换回来)。我在Windows Phone 8.1项目中使用了这个解决方案,不确定Windows应用商店的应用程序,但我相信它会起作用。

public object Convert(object value, Type targetType, object parameter, string culture)
    {
        // Whatever byte[] you're trying to convert.
        byte[] imageBytes = (value as FileAttachment).ContentBytes;
        BitmapImage image = new BitmapImage();
        InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
        ms.AsStreamForWrite().Write(imageBytes, 0, imageBytes.Length);
        ms.Seek(0);
        image.SetSource(ms);
        ImageSource src = image;
        return src; 
    }

最新更新