从Windows Phone UWP的WriteableBitmap创建BitmapDecoder时发生异常

本文关键字:BitmapDecoder 异常 创建 WriteableBitmap Windows Phone UWP | 更新日期: 2023-09-27 18:30:03

在我的UWP Windows 10 Mobile应用程序中,我试图访问和操作给定WriteableBitmap的PixelBuffer中各个像素的透明度。我遇到的问题是BitmapDecoder.CreateAsync()正在抛出

"找不到该组件。(HRESULT中出现异常:0x88982F50)"。

我花了太多时间搜索、重构和调试,但都无济于事;任何形式的提示、指导或帮助都将不胜感激。

        // img is a WriteableBitmap that contains an image
        var stream = img.PixelBuffer.AsStream().AsRandomAccessStream();
        BitmapDecoder decoder = null;
        try
        {
            decoder =  await BitmapDecoder.CreateAsync(stream);
        }
        catch(Exception e)
        {
            // BOOM: The component cannot be found. (Exception from HRESULT: 0x88982F50)
        }
        // Scale image to appropriate size 
        BitmapTransform transform = new BitmapTransform()
        {
            ScaledWidth = Convert.ToUInt32(img.PixelWidth),
            ScaledHeight = Convert.ToUInt32(img.PixelHeight)
        }; 
        PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
            BitmapPixelFormat.Bgra8, // WriteableBitmap uses BGRA format 
            BitmapAlphaMode.Straight,
            transform,
            ExifOrientationMode.IgnoreExifOrientation, // This sample ignores Exif orientation 
            ColorManagementMode.DoNotColorManage
        );
        // An array containing the decoded image data, which could be modified before being displayed 
        byte[] pixels = pixelData.DetachPixelData();  

更新:如果这有助于激发一些想法,我发现如果我使用为编解码器提供流的重载CreateAsync构造函数,它会抛出一个不同的异常:

指定的强制转换无效。

            Guid BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
            decoder =  await BitmapDecoder.CreateAsync(BitmapEncoderGuid, stream);  

无论我提供哪种编解码器(例如Png、Jpeg、GIF、Tiff、Bmp、JpegXR),它都会给出相同的例外

从Windows Phone UWP的WriteableBitmap创建BitmapDecoder时发生异常

我不明白你为什么要使用BitmapDecoderWriteableBitmap中的像素数据没有以任何方式进行编码。如果您从特定压缩格式的文件流加载图像,则需要BitmapDecoder,这需要使用正确的编解码器。

您可以直接从流中读取像素数据:

byte[] pixels;
using (var stream = img.PixelBuffer.AsStream())
{
    pixels = new byte[(uint)stream.Length];
    await stream.ReadAsync(pixels, 0, pixels.Length);
}

这将为您提供一个byte数组,每个像素包含4个字节,对应于它们的R、G、B和a分量。