I am trying to get the RGB value of each pixel in WinRT app. I can access an array of bytes containing PixelData
but I don't know how to work with that so how can I extract the RGB information from the byte array?
var bd = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
var pd = await bd.GetPixelDataAsync();
var tempBuffer = pd.DetachPixelData();
var PixelMatrix = new byte[bd.PixelWidth, bd.PixelHeight];
// how do I get the RGB value for PixelMatrix[0,0]?
Since you have a RGB image,
tempBuffer[k + 0]
is the red channel,tempBuffer[k + 1]
is the green channel, andtempBuffer[k + 2]
is the blue channel, i.e.tempBuffer
is a 1D array. If you were looping over all the pixels, the pseudo code for this would be:Since the Marshal class isn't available on WinRT - the most performant way to proceed would be to use a SafeMemoryMappedViewHandle (SafeBuffer).
This method can also handle pixelformats with multi-byte components without needing to use a BinaryReader and reading it component by component (RGBA16 with 16 bits per component). Find out what the pixel format is using the decoder's BitmapPixelFormat property and use the appropriately declared structure.
Note: This method can also be a replacement for any operation that requires Marshal.PtrToStructure or some such equivalent on WinRT.