Search code examples
c#uwpdirectxdirectx-11win2d

Initializing CanvasBitmap UWP


I'm trying to convert SoftwareBitmap into CanvasBitmap (on UWP). But when I used BitmapPixelFormat.Bgra8 && BitmapAlphaMode.Premultiplied, I got an error like unsupported pixel format or alpha mode.

I decided to try all possible formats with following code:

if (softwareBitmap != null)
{
    var wasSuccess = false;
    foreach (var bitmapAlphaMode in new[] {BitmapAlphaMode.Straight, BitmapAlphaMode.Premultiplied, 
                                           BitmapAlphaMode.Ignore})
    {
        foreach (var bitmapPixelFormat in new[] { 
            BitmapPixelFormat.Bgra8, BitmapPixelFormat.Gray8, BitmapPixelFormat.Gray16, 
            BitmapPixelFormat.Yuy2, BitmapPixelFormat.Rgba8, BitmapPixelFormat.Rgba16, 
            BitmapPixelFormat.Nv12, BitmapPixelFormat.P010, BitmapPixelFormat.Unknown
        })
        {
            if (wasSuccess)
            {
                break;
            }
            try
            {
                SoftwareBitmap.Convert(softwareBitmap, bitmapPixelFormat, bitmapAlphaMode);
                var bitmap = CanvasBitmap.CreateFromSoftwareBitmap(
                    _canvasDevice, 
                    softwareBitmap
                );
                wasSuccess = bitmap != null;
            }
            catch (Exception ex)
            {
            }
        }
    }
} 

But after all possible attempt's, wasSuccess is false. (_canvasDevice was initialized successfully, that's not the problem).

How can it be?


Solution

  • But after all possible attempt's, wasSuccess is false. (_canvasDevice was initialized successfully, that's not the problem).

    Not all BitmapPixelFormats are supported by CanvasBitmap, please refer to CreateFromSoftwareBitmap document remarks part , You could find BitmapPixelFormat.Unknown BitmapPixelFormat.Gray16 BitmapPixelFormat.Nv12 BitmapPixelFormat.Yuy2 is not supported.

    And not all AlphaModes are available for CanvasBitmap, please refer to this document. You will find CanvasBitmap compatible with Premultiplied, Ignore alpha mode. Only A8UIntNormalized A8UIntNormalized support Straight alpha mode.

    By the way, there is an error in SoftwareBitmap.Convert method in above code segment. You should assign the return value to softwareBitmap like following, or it will never update softwareBitmap property.

    softwareBitmap =  SoftwareBitmap.Convert(softwareBitmap, bitmapPixelFormat, bitmapAlphaMode);