Why can't my WritableBitmap be found through the IRandomAccessStream?

0

I have a WritableBitmap that was created from a snapshot from a webcam. I want to load it into a BitmapDecoder so I can crop the image. Here is the code:

IRandomAccessStream ras = displaySource.PixelBuffer.AsStream().AsRandomAccessStream();
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ras); //Fails Here

displaySource is the WritableBitmap from the webcam and the exception I get is

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

This is odd to me because I can load displaySource onto my GUI, I just can't use this code. I have tried switching it to InMemoryRandomAccessStream as well. There is not any stackoverflow solution for this exception from what I see.

The displaySource is generated from this code:

                // Create a WritableBitmap for our visualization display; copy the original bitmap pixels to wb's buffer.
                // Note that WriteableBitmap doesn't support NV12 and we have to convert it to 32-bit BGRA.
                using (SoftwareBitmap convertedSource = SoftwareBitmap.Convert(previewFrame.SoftwareBitmap, BitmapPixelFormat.Bgra8))
                {
                    displaySource = new WriteableBitmap(convertedSource.PixelWidth, convertedSource.PixelHeight);
                    convertedSource.CopyToBuffer(displaySource.PixelBuffer);
                }

where preview frame is a VideoFrame setup from the webcam.

Thanks in advance.

c#
bitmap
stream
win-universal-app
asked on Stack Overflow Nov 6, 2015 by Seth Kitchen • edited Nov 6, 2015 by Seth Kitchen

1 Answer

2

The WriteableBitmap.PixelBuffer is already decoded into a buffer of BGRA pixels.

BitmapDecoder expects a decoded image (.bmp, .png, .jpg, etc.) and produces a pixel buffer. BitmapEncoder takes a pixel buffer and produces an encoded image.

You could roundtrip by calling BitmapEncoder to encode to .png (don't use a lossy format such as jpg) and then BitmapDecoder to decode. If your goal is to save out the cropped image then just use BitmapEncoder. Both classes can apply a BitmapTransform.

If all you want to do is crop then roundtripping through a bitmap format is overkill. It'd be pretty easy to just copy the pixels you want out of the PixelArray. If you don't want to write it yourself, the open-source library WriteableBitmapEx provides extensions to WriteableBitmap and has a Crop method:

// Crops the WriteableBitmap to a region starting at P1(5, 8) and 10px wide and 10px high
var cropped = writeableBmp.Crop(5, 8, 10, 10);
answered on Stack Overflow Nov 7, 2015 by Rob Caplan - MSFT

User contributions licensed under CC BY-SA 3.0