简体   繁体   中英

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM