代码之家  ›  专栏  ›  技术社区  ›  TDNG

从字节数组创建位图图像,并将其显示在图像对象UWP Raspberry Pi 3上

  •  3
  • TDNG  · 技术社区  · 7 年前

    我使用以下代码在文件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();
                }
            }
        }
    

    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毫秒来完成这个过程,这是很长的时间。 调试程序可能会减慢进程?我正在使用Visual Studio 2015。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Michael Xu    7 年前

    您可以在中将数据缓冲区(arrayImmagine)传输到图像 InMemoryRandomAccess流 .这些代码大约需要200毫秒。我用以下代码进行了测试。此外,您可以参考此 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;