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

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


Problem/Question/Abstract:

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

Answer:

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):
  Boolean;
type
  TBitmapHeaders = packed record
    FileHeader: TBitmapFileHeader;
    case Integer of
      2: (CoreHeader: TBitmapCoreHeader);
      3: (InfoHeader: TBitmapInfoHeader);
  end;
var
  fs: TFileStream;
  Headers: TBitmapHeaders;
begin
  Result := False;
  fs := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite);
  try
    f.ReadBuffer(Headers, SizeOf(Headers));
    {Check the bitmap}
    { ... }
    {Get the size}
    case Headers.CoreHeader.bcSize of
      SizeOf(TBitmapCoreHeader):
        begin
          Width := Headers.CoreHeader.bcWidth;
          Height := Headers.CoreHeader.bcHeight;
          Result := True;
        end;
      SizeOf(TBitmapInfoHeader), SizeOf(TBitmapV4Header), SizeOf(TBitmapV5Header):
        begin
          Width := Headers.InfoHeader.biWidth;
          {Negative Height values are possible -> Abs}
          Height := Abs(Headers.InfoHeader.biHeight);
          Result := True;
        end;
    else
      {Place a special error message, i.e. wrong header, here}
    end;
  finally
    f.Free;
  end;
end;

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