为什么无法通过 IRandomAccessStream 找到我的 WritableBitmap?

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

我有一个 WritableBitmap,它是根据网络摄像头的快照创建的。我想将它加载到 BitmapDecoder 中,以便裁剪图像。这是代码:

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

displaySource 是来自网络摄像头的 WritableBitmap,我得到的异常是

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

这对我来说很奇怪,因为我可以将 displaySource 加载到我的 GUI 上,但我不能使用这段代码。我也试过将它切换到 InMemoryRandomAccessStream 。据我所知,没有针对此异常的任何 Whosebug 解决方案。

displaySource 是从此代码生成的:

                // 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);
                }

其中预览帧是来自网络摄像头的 VideoFrame 设置。

提前致谢。

WriteableBitmap.PixelBuffer 已经解码到 BGRA 像素缓冲区。

BitmapDecoder 需要解码图像(.bmp、.png、.jpg 等)并生成像素缓冲区。 BitmapEncoder 采用像素缓冲区并生成编码图像。

您可以通过调用 BitmapEncoder 编码为 .png(不要使用有损格式,例如 jpg)然后调用 BitmapDecoder 进行解码来进行往返。如果您的目标是保存裁剪后的图像,那么只需使用 BitmapEncoder。 类 都可以应用 BitmapTransform。

如果您想做的只是裁剪,那么通过位图格式进行往返就太过分了。从 PixelArray 中复制您想要的像素非常容易。如果你不想自己写,开源库 WriteableBitmapEx 提供了 WriteableBitmap 的扩展,并且有一个 Crop 方法:

// 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);