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

孤街浪徒 提交于 2020-01-24 09:06:08

问题


I'm using this code to write a Byte Array inside a file 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();
            }
        }
    }

Then i'm using this code to display the BMP image in a Image object

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

these functions take about 400 milliseconds to complete the process, that's a lot of time. Is there a way to avoid the usage of a BMP file and use only a stream to display the image on the image object? It can be that debugging the program can slow the processes? I'm using Visual Studio 2015.


回答1:


You can transfer the data buffer(arrayImmagine) to image in InMemoryRandomAccessStream.These codes take about 200ms.I tested with following pieces of code. In addition, you can reference this article to get more information.

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

        image.Source = biSource;


来源:https://stackoverflow.com/questions/46662578/create-a-bitmapimage-from-a-byte-array-and-display-it-on-an-image-object-uwp-ras

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!