How to get dimensions of image file in Delphi?

Srdjan Vukmirica picture Srdjan Vukmirica · Mar 4, 2013 · Viewed 12.5k times · Source

I want to know width and height of an image file before opening that file.

So, how to do that?

EDIT: This refers to jpg, bmp, png and gif types of image files.

Answer

Andreas Rejbrand picture Andreas Rejbrand · Mar 4, 2013

If by 'image file' you mean those raster image files recognised by the VCL's graphics system, and by 'before opening' you mean 'before the user is likely to notice that the file is opened', then you can do this very easily:

var
  pict: TPicture;
begin
  with TOpenDialog.Create(nil) do
    try
      if Execute then
      begin
        pict := TPicture.Create;          
        try
          pict.LoadFromFile(FileName);
          Caption := Format('%d×%d', [pict.Width, pict.Height])
        finally
          pict.Free;
        end;
      end;
    finally
      Free;
    end;

Of course, the file is opened, and this requires a lot of memory if the image is big. However, if you need to obtain metatada (like dimensions) without loading the file, I believe you need a more 'complicated' solution.