2008. május 5., hétfő

Get the width and height of a bitmap without opening the file


How to get the width and height of a bitmap without opening the file


A bitmap starts with a file header (TBitmapFileHeader). Then followed by a bitmap info header, dependent on the bitmap version. The first DWORD contains the size of the info structure, so you can read and analyze this to chose the correct handling. Bitmap version 2 uses a TBitmapCoreHeader. The width and height value follow in the next two Words. Version 3 uses a TBitmapInfoHeader, version 4 a TBitmapV4Header and version 5 a TBitmapV5Header. In all these headers the width and height follow in the next two LongInts.

You can use this information to build a function to get at the width and height data. The following is untested and you should add a check, to see whether the file is a bitmap or not:

function GetBitmapSizeFromFile(const Filename: string; var Width, Height: Integer):
  TBitmapHeaders = packed record
    FileHeader: TBitmapFileHeader;
    case Integer of
      2: (CoreHeader: TBitmapCoreHeader);
      3: (InfoHeader: TBitmapInfoHeader);
  fs: TFileStream;
  Headers: TBitmapHeaders;
  Result := False;
  fs := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite);
    f.ReadBuffer(Headers, SizeOf(Headers));
    {Check the bitmap}
    { ... }
    {Get the size}
    case Headers.CoreHeader.bcSize of
          Width := Headers.CoreHeader.bcWidth;
          Height := Headers.CoreHeader.bcHeight;
          Result := True;
      SizeOf(TBitmapInfoHeader), SizeOf(TBitmapV4Header), SizeOf(TBitmapV5Header):
          Width := Headers.InfoHeader.biWidth;
          {Negative Height values are possible -> Abs}
          Height := Abs(Headers.InfoHeader.biHeight);
          Result := True;
      {Place a special error message, i.e. wrong header, here}

The pixel data start at the file position Headers.FileHeader.bfOffBits. Read the data from the file. For more information on the pixel data, read the WinAPI help, e.g. the topic BITMAPINFOHEADER.

Nincsenek megjegyzések:

Megjegyzés küldése