Title: Get images (GIF/JPG) dimensions
Question: Get width and height of GIF/JPG images stored as arrays of bytes.
Optimized to use within server apps.
Answer:
function GetJpegSize(a: array of byte; var width, height: integer): boolean;
var
i, n: integer;
begin
n := length(a) - 8;
i := 1;
while (i case a[i + 1] of
$C0 .. $C3: //Goal block
begin
height := a[i + 5] * 256 + a[i + 6];
width := a[i + 7] * 256 + a[i + 8];
Result := True;
exit;
end;
$FF: //Nop block
inc(i);
$D0 .. $D9, $01: //Info block
inc(i, 2);
else //Normal block
inc(i, a[i + 2] * 256 + a[i + 3] + 2);
end;
Result := False;
end;
function GetGifSize(a: array of byte; var width, height: integer): boolean;
begin
Result := (a[1] = $47) and (a[2] = $49) and (a[3] = $46); //'GIF' Signature
width := a[8] * 256 + a[7];
height := a[10] * 256 + a[9];
end;
Functions return False if file is corrupted.
Usage:
var
f: file;
i, x, y: integer;
a: array of byte;
begin
assignfile(f, YOUR_GIF_FILENAME);
reset(f, 1);
i := filesize(f);
setlength(a, i);
blockread(f, a[1], i);
if GetGIFSize(a, x, y) then
writeln('Width ', x, ' Height ',y)
else
writeln('Error');
closefile(f);
readln;
end.