获取JPEG的宽度、高度等信息
{ Copyright Kingron 2002 }
function GetJPEGSize(FileName: string; var Width, Height: WORD): Boolean;
const
JPEG_FLAG_BEGIN = $D8FF;
JPEG_FLAG_END = $D9FF;
JPEG_FRAME = $C0FF;
var
FS: TFileStream;
Flag1, Flag2: WORD;
B: Byte;
procedure SeekForFrame;
type
TSegHeader = packed record
Flag: WORD;
LenHi, LenLo: Byte;
end;
var
Seg: TSegHeader;
begin
with Seg, FS do
repeat
Read(Seg, SizeOf(Seg));
if Flag <> JPEG_FRAME then
Position := Position + MakeWord(LenLo, LenHi) - 2;
until (Position >= Fs.Size) or (Seg.Flag = JPEG_FRAME);
end;
begin
FS := TFileStream.Create(FileName, fmOpenRead);
try
{ JPEG 文件开头必须为 FF D8,文件尾必须为 FF D9 }
FS.Read(Flag1, SizeOf(Flag1));
FS.Position := FS.Size - 2;
FS.Read(Flag2, SizeOf(Flag2));
Result := (Flag1 = JPEG_FLAG_BEGIN) and (Flag2 = JPEG_FLAG_END);
if not Result then exit; { 不是合法的JPEG文件则退出 }
FS.Position := 2;
SeekForFrame; { 寻找JPEG的Frame段,即图像数据区 }
FS.Read(B, SizeOf(B)); { Frame段段头后第一个Byte为数据精度 }
FS.Read(B, SizeOf(B)); { 高度高字节 }
WordRec(Height).Hi := B;
FS.Read(B, SizeOf(B)); { 高度低字节 }
WordRec(Height).Lo := B;
FS.Read(B, SizeOf(B)); { 宽度高字节 }
WordRec(Width).Hi := B;
FS.Read(B, SizeOf(B)); { 宽度低字节 }
WordRec(Width).Lo := B;
finally
FS.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
W, H: Word;
begin
with OpenDialog1 do
if Execute then
if GetJPEGSize(FileName, W, H) then
Caption := Format('Yes,W:%d,H:%d', [W, H])
else Caption := 'No';
end;