Metre
Metre

Reputation: 25

Delphi isn't writing my file header properly

I thought instead of using TImage with an 8bit BMP I'd save my own Bitmap - which I have done with Delphi a few times before. But for some reason I cannot figure out, the first two bytes of the file is always written as four bytes! My record for the header is

type
 BitmapH = Record
  head : WORD;
  filesize : DWORD;
  reserved : DWORD;
  bmpoffset : DWORD;
  bmpheadersize : DWORD;
  width : DWORD;
  height : DWORD;
  planes : WORD;
  bpp : word;
  comp : longint;
  bmdatasize : longint;
  hres : longint;
  vres : longint;
  numofcolors : longint;
  importantcolors : longint;
  palette : array[0..1023] of byte;
 end;

I've tried even changing it to a 2 byte array still no go. Even with it changed to just head : byte; it still writes 1 byte then pushes junk to the next 3. I must be missing something simple!

Here's how I am writing the file header -

var BM : file of BitmapH;
var BMD : file of byte;
var header : BitmapH;
var i : integer;
var test : byte;
begin

  AssignFile(BM, 'd:\test.bmp');
  Rewrite(BM);

  header.head := 19778;
//  header.head[1] := 'M';
  header.filesize := 2102;
  header.reserved := 0;
  header.bmpoffset := 1080;
  header.bmpheadersize := 40;
  header.width := 32;
  header.height := 32;
  header.planes := 1;
  header.bpp := 8;
  header.comp := 0;
  header.bmdatasize := 1024;
  header.hres := 100;
  header.vres := 100;
  header.numofcolors := 0;
  header.importantcolors := 0;

  for i := 0 to 255 do
  begin
    header.palette[i*4] := getBvalue(palette[i]);
    header.palette[(i*4) + 1] := getBvalue(palette[i]);
    header.palette[(i*4) + 2] := getBvalue(palette[i]);
    header.palette[(i*4) + 3] := 0;
  end;

  Write(BM, header);

Sorry for the crudeness, it's just a test :)

Any help is appreciated!

PS - The reason for not using TImage to save is because I am changing the palette on the fly which seems like a hassle to edit via TImage.

Upvotes: 1

Views: 391

Answers (2)

Novakov
Novakov

Reputation: 3095

Add packed keyword to record to indicate that it's content should not be aligned:

BitmapH = packed Record

Upvotes: 3

Ondrej Kelle
Ondrej Kelle

Reputation: 37211

Use packed record to avoid the default memory alignment.

Upvotes: 8

Related Questions