0

I want to get a BitmapImage when capture view's screenshot. So I start to get byte array data first, then convert to 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;
            }
        }

But it give error :

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

Please help me to find the problem.

2
  • Which line throw this error within above code ? Commented Dec 15, 2020 at 9:24
  • @NicoZhu-MSFT That's await bitmapImage.SetSourceAsync(stream); Commented Dec 15, 2020 at 9:48

1 Answer 1

1

Error when convert byte array to BitmapImage in UWP

The problem is you have not specific BitmapEncoder for BitmapImage when convertering. In general, we often use the following code to get BitmapImage from bytes.

_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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.