Reading .bmp image pixel colors doesn't work with 4 bit image

I have this code that selects an image and reads its parameters.

#include <SPI.h>
#include <SD.h>

File bmpImage;

void setup()
{
  Serial.begin(9600);

  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    return;
  }

  // Open
  bmpImage = SD.open("test.bmp", FILE_READ);

  // Width
  bmpImage.seek(18);
  Serial.print("Width: ");
  Serial.println(bmpImage.read());

  // Height
  bmpImage.seek(22);
  Serial.print("Height: ");
  Serial.println(bmpImage.read());

  // RGB bits
  bmpImage.seek(28);
  Serial.print("RGB bits: ");
  Serial.println(bmpImage.read());

  // First pixel
  bmpImage.seek(54);
  Serial.print("Color B: ");
  Serial.println(bmpImage.read());
  bmpImage.seek(55);
  Serial.print("Color G: ");
  Serial.println(bmpImage.read());
  bmpImage.seek(56);
  Serial.print("Color R: ");
  Serial.println(bmpImage.read());
  
  // Close
  bmpImage.close();
}

void loop()
{
  
}

I tried this code with 2 images, an image with 4 bit colors, and an image with 24 bit colors.
this code works with the 24 bit image, it shows me that the BGR color of the first pixel is (76, 177, 34), but with the 4 bit image is shows me (0, 0, 0).

Screenshot_62
Screenshot_63

The code is probably not correct. There are several options for BMP file headers.

See this summary: BMP file format - Wikipedia

1 Like

The Wikipedia article above says that there is a mandatory color lookup table since the pixel size is less than 8.

4-bit pixels will have a 16-entry color table and each of those entries will be 4 bytes long. That will make the table 64 bytes so your pixels will start closer to 118 bytes into the file. Two pixels per byte instead of three bytes per pixel.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.