在 UWP 中将字节数组转换为 BitmapImage 时出错

Error when convert byte array to BitmapImage in UWP

我想在捕获视图的屏幕截图时得到一个 BitmapImage。所以我开始先获取字节数组数据,再转成BitmapImage。

RenderTargetBitmap renderTarget = new RenderTargetBitmap();
await renderTarget.RenderAsync(swapChainPanel);    
IBuffer pixelBuffer = await renderTarget.GetPixelsAsync();

await GetBitmapAsync(pixelBuffer.ToArray());
...
public static async Task<BitmapImage> GetBitmapAsync(byte[] data)
        {
            var bitmapImage = new BitmapImage();

            try
            {
                using (var stream = new InMemoryRandomAccessStream())
                {
                    using (var writer = new DataWriter(stream))
                    {
                        writer.WriteBytes(data);
                        await writer.StoreAsync();
                        await writer.FlushAsync();
                        writer.DetachStream();
                    }

                    stream.Seek(0);
                    await bitmapImage.SetSourceAsync(stream); // throw Exception
                }

                return bitmapImage;
            }
            catch (Exception e)
            {
                return null;
            }
        }

但它给出错误:

The component cannot be found. (Exception from HRESULT: 0x88982F50)

请帮我找出问题。

Error when convert byte array to BitmapImage in UWP

问题是您在转换时没有为 BitmapImage 指定 BitmapEncoder。一般情况下,我们经常使用下面的代码从bytes中得到BitmapImage

_backAction = new Action<byte[]>(async (bytes) =>
{
    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();     
    BitmapImage img = new BitmapImage();
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
    encoder.SetPixelData(
        BitmapPixelFormat.Bgra8,
        BitmapAlphaMode.Straight,
        (uint)48,
        (uint)32,
        DisplayInformation.GetForCurrentView().LogicalDpi,
        DisplayInformation.GetForCurrentView().LogicalDpi,
        bytes);
    await encoder.FlushAsync();
    await img.SetSourceAsync(stream);
});