从 Byte 数组创建 BitmapImage 并将其显示在 Image 对象上 UWP Raspberry Pi 3

Create a BitmapImage from a Byte array and display it on an Image object UWP Raspberry Pi 3

我正在使用这段代码在文件 BMP 中写入一个字节数组:

private async void ScriviBMP()
    {
        using (Stream stream = immagineBitmap.PixelBuffer.AsStream())
        {
            await stream.WriteAsync(arrayImmagine, 0, arrayImmagine.Length);
        }
        StorageFolder folder = KnownFolders.PicturesLibrary;
        if (folder != null)
        {
            StorageFile file = await folder.CreateFileAsync("area2_128x128" + ".bmp", CreationCollisionOption.ReplaceExisting);
            using (var storageStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, storageStream);
                var pixelStream = immagineBitmap.PixelBuffer.AsStream();
                var pixels = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)immagineBitmap.PixelWidth, (uint)immagineBitmap.PixelHeight, 48, 48, pixels);
                await encoder.FlushAsync();
            }
        }
    }

然后我使用这段代码在 Image 对象中显示 BMP 图像

private async void VisBMP()
    {
        var file = await KnownFolders.PicturesLibrary.GetFileAsync("area2_128x128.bmp");
        using (var fileStream = (await file.OpenAsync(Windows.Storage.FileAccessMode.Read)))
        {
            var bitImg = new BitmapImage();
            //bitImg.UriSource = new Uri(file.Path);
            bitImg.SetSource(fileStream);
            image.Source = bitImg;
        }
    }

这些函数大约需要 400 毫秒才能完成,这是很多时间。 有没有办法避免使用 BMP 文件并仅使用流在图像对象上显示图像? 调试程序会减慢进程吗?我正在使用 Visual Studio 2015.

您可以将数据缓冲区 (arrayImmagine) 传输到 InMemoryRandomAccessStream 中的图像。这些代码大约需要 200ms.I 测试以下代码片段。此外,您可以参考此article以获取更多信息。

        BitmapImage biSource = new BitmapImage();
        using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
        {
            await stream.WriteAsync(bytes.AsBuffer());
            stream.Seek(0);
            await biSource.SetSourceAsync(stream);
        }

        image.Source = biSource;