将RenderTargetBitmap转换为要在嵌入式屏幕上显示的byte []?

时间:2016-11-26 16:03:21

标签: c# arrays bitmap windowsiot

我正在尝试将RenderTargetBitmap转换为字节数组,然后将其发送到外部单色OLED屏幕。我知道为了正确显示位图,位/字节对齐应该是LSB到MSB&从上到下:

enter image description here

但我无法弄清楚如何以该格式获取RenderTargetBitmap的pixeldata。

目前我已经:

        RenderTargetBitmap renderTargetBitmap; //This is already set higher up
        DataReader reader = DataReader.FromBuffer(await renderTargetBitmap.GetPixelsAsync());

        // Placeholder for reading pixels
        byte[] pixel = new byte[4]; // RGBA8

        // Write out pixels
        int index = 0;
        byte[] array = new byte[renderTargetBitmap.PixelWidth*renderTargetBitmap.PixelHeight];
        using (reader)
        {
            //THIS IS WHERE I THINK I'M SCREWING UP
            for (int x = 0; x < rHeight; x++)
            {
                for (int y = 0; x < rWidth; y++)
                {
                    reader.ReadBytes(pixel);
                    if (pixel[2] == 255)
                        array[index] = 0xff;
                    else
                        array[index] = 0x00;
                    index++;
                }
            }
        }
        sh1106.ShowBitmap(buffer); //Send off the byte array

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,这就是我做的工作(它会将BGRA8输出转换为1BPP输出,然后可以在单色显示器上使用,在我的情况下是SSD1306)

在1BPP输出意味着8个像素存储在1个字节中。所以你需要将每4个字节转换成1位。

  public async Task Draw()
  {
     ActiveCanvas.UpdateLayout();
     ActiveCanvas.Measure(ActiveCanvas.DesiredSize);
     ActiveCanvas.Arrange(new Rect(new Point(0, 0), ActiveCanvas.DesiredSize));

     // Create a render bitmap and push the surface to it
     RenderTargetBitmap renderBitmap = new RenderTargetBitmap();
     await renderBitmap.RenderAsync(ActiveCanvas, (int)ActiveCanvas.DesiredSize.Width, (int)ActiveCanvas.DesiredSize.Height);

     DataReader bitmapStream = DataReader.FromBuffer(await renderBitmap.GetPixelsAsync());

     if (_device != null)
     {
        byte[] pixelBuffer_1BPP = new byte[(int)(renderBitmap.PixelWidth * renderBitmap.PixelHeight) / 32];

        pixelBuffer_1BPP.Initialize();

        using (bitmapStream)
        {
           while (bitmapStream.UnconsumedBufferLength > 0)
           {
              uint index = (uint)(renderBitmap.PixelWidth * renderBitmap.PixelHeight * 4) - bitmapStream.UnconsumedBufferLength;

              for (int bit = 0; bit < 8; bit++)
              {
                 bitmapStream.ReadBytes(BGRA8);

                 byte value = (byte)(((BGRA8[0] & 0x80) | (BGRA8[1] & 0x80) | (BGRA8[2] & 0x80)) == 0x80 ? 1 : 0);

                 pixelBuffer_1BPP[index] |= (byte)(value << (7 - bit));
              }
           }

           _device.DrawBitmap(0, 0, pixelBuffer_1BPP, (short)renderBitmap.PixelWidth, (short)renderBitmap.PixelHeight, Colors.White);
        }
     }
  }