簡體   English   中英

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

但它給出了錯誤:

找不到該組件。 (HRESULT 異常:0x88982F50)

請幫我找出問題所在。

在 UWP 中將字節數組轉換為 BitmapImage 時出錯

問題是您在轉換時沒有針對BitmapImage的特定BitmapEncoder 一般來說,我們經常使用下面的代碼從字節中獲取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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM