从字节数组创建BitmapImage并在Image对象上显示它的UWP Raspberry Pi 3。

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

然后我使用这段代码将BMP图像显示在Image对象中。
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。


1
immagineBitmap是一个WriteableBitmap吗?如果是,那么您可以直接将其分配给Image控件的Source属性,如 image.Source = immagineBitmap; - Clemens
这个问题(以及@michael-xu-msft的答案)对于所有UWP应用程序都是相关的,而不仅仅是树莓派3。 - Yoav Feuerstein
1个回答

3
您可以将数据缓冲区(arrayImmagine)转换为InMemoryRandomAccessStream中的图像。这些代码大约需要200毫秒。我使用以下代码进行测试。此外,您可以参考此文章获取更多信息。
        BitmapImage biSource = new BitmapImage();
        using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
        {
            await stream.WriteAsync(bytes.AsBuffer());
            stream.Seek(0);
            await biSource.SetSourceAsync(stream);
        }

        image.Source = biSource;

虽然这是真的,但它似乎完全多余。OP肯定可以直接将他们的WriteableBitmap分配给Image的Source。 - Clemens
我尝试直接将WriteableBitmap分配给Image的Source,但它无法正确显示图像。 - Michael Xu

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