ChangeColour

There are several types of .bmp file. Umbrella.bmp has four bits per pixel. Each combination of four bits represents one of the 16 colours in the colour table. Only a few lines of code are required to change a colour. This program reads and outputs data from the header before seeking and changing one byte. That is all that is necessary to change the colour of every bright red pixel in the umbrella on the left to obtain the image on the right.

BlockRead is a useful procedure for reading different data types from a file. Note that the file type to enable BlockRead is just file and not file of byte. You need a copy of umbrella.bmp in your program folder. We obtained the original from Clker.com.

program ChangeColour;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
type
  TRGBQuad = record
               Blue, Green, Red, Reserved : byte;
             end;
var
  BMPFile : file;
  Init1, Init2 : char;
  FileSize, DummyInt, StartData, Width, Height, Count : integer;
  DummySmallInt, BitsPerPixel : smallint;
  ColourTable: Array [1..16] of TRGBQuad;
  DullRed : byte = 170;

begin
  assignfile(BMPFile, 'umbrella.bmp');
  reset(BMPFile, 1); //Minimum size of read is 1 byte
  //Read and output data from file header
  blockRead(BMPFile, Init1, 1);
  blockRead(BMPFile, Init2, 1);
  //BMP should start with 'BM'
  writeln('First two characters: ', Init1, Init2);
  blockRead(BMPFile, FileSize, 4);
  writeln('File size in bytes: ', FileSize);
  blockRead(BMPFile, DummyInt, 4); //Move on 4 bytes
  blockRead(BMPFile, StartData, 4);
  writeln('Start of Data: ', StartData);
  blockRead(BMPFile, DummyInt, 4); //Move on 4 bytes
  blockRead(BMPFile, Width, 4);
  blockRead(BMPFile, Height, 4);
  writeln('Width: ', Width);
  writeln('Height: ', Height);
  blockRead(BMPFile, DummySmallInt, 2); //Move on 2 bytes
  blockRead(BMPFile, BitsPerPixel, 2);
  writeln('BitsPerPixel: ',  BitsPerPixel);
  if BitsPerPixel = 4 then
    begin
      seek(BMPFile, 54); //Start of colour table
      blockRead(BMPFile, ColourTable, 64);
      //Output colour table
      for Count := 1 to 16 do
        begin
          with ColourTable[Count] do
            begin
              writeln(Count,'- Blue: ', Blue, ', Green: ',
                     Green, ', Red : ', red);
            end;
        end;
      //Change bright red to dull red  
      seek(BMPFile, 92);  //Red byte of bright red in colour table
      blockWrite(BMPFile, DullRed, 1);
    end;
  closeFile(BMPFile);
  readln;
end.
Programming - a skill for life!

Changing colours, copying images and hiding data