NV12 Format support in Bitmapimage C#

1.6k Views Asked by At

Does BitmapImage or WriteableBitmapImage supports NV12 format. or Can we create a BitmapImage or WriteableBitmapImage from a byte array which is arranged in NV12 format?

Thanks

2

There are 2 best solutions below

0
On

No. NV12 is not in the supported PixelFormats.

You will have to convert your byte array to a supported pixel format first. This answer shows how to do that for YUV and might help you writing a similar method to convert from NV12.

EDIT:

Here is C++ code to convert NV21 (!) to RGB. The only difference to NV12 is the order of the U and V values, hence that would be easy to adapt.

0
On

Sliding in from the future with this answer.

This method converts a byte[] array of NV12 data to a BMP image.

public static Bitmap TransformNv12ToBmpFaster(byte[] data, int width, int height, IGraphLogger logger)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            var bmp = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
            var bmpData = bmp.LockBits(
                new Rectangle(0, 0, bmp.Width, bmp.Height),
                ImageLockMode.ReadWrite,
                PixelFormat.Format32bppRgb);

            var uvStart = width * height;
            for (var y = 0; y < height; y++)
            {
                var pos = y * width;
                var posInBmp = y * bmpData.Stride;
                for (var x = 0; x < width; x++)
                {
                    var vIndex = uvStart + ((y >> 1) * width) + (x & ~1);

                    //// https://msdn.microsoft.com/en-us/library/windows/desktop/dd206750(v=vs.85).aspx
                    //// https://en.wikipedia.org/wiki/YUV
                    var c = data[pos] - 16;
                    var d = data[vIndex] - 128;
                    var e = data[vIndex + 1] - 128;
                    c = c < 0 ? 0 : c;

                    var r = ((298 * c) + (409 * e) + 128) >> 8;
                    var g = ((298 * c) - (100 * d) - (208 * e) + 128) >> 8;
                    var b = ((298 * c) + (516 * d) + 128) >> 8;
                    r = r.Clamp(0, 255);
                    g = g.Clamp(0, 255);
                    b = b.Clamp(0, 255);

                    Marshal.WriteInt32(bmpData.Scan0, posInBmp + (x << 2), (b << 0) | (g << 8) | (r << 16) | (0xFF << 24));
                    pos++;
                }
            }

            bmp.UnlockBits(bmpData);

            watch.Stop();
            logger.Info($"Took {watch.ElapsedMilliseconds} ms to lock and unlock");

            return bmp;
        }

I got this the Microsoft Graph Samples repo, here.