[教程] Delphi 中 TJpegImage 中的一处问题修复

Delphi 中检测 JPEG 图片格式流的原始代码如下:

class function TJPEGImage.CanLoadFromStream(Stream: TStream): Boolean;
var
  soi, marker: Word;
  P: Int64;
begin
  P := Stream.Position;
  try
    Result := (Stream.Read(soi, SizeOf(soi)) = SizeOf(soi)) and (soi = $D8FF) and
      (Stream.Read(marker, SizeOf(marker)) = SizeOf(marker)) and (marker and $E0FF = $E0FF);
  finally
    Stream.Position := P;
  end;
end;

同时检查了 soi 和 marker,但是 marker 的值实际上是没有保证的。所以正确的做法是去掉对 marker 的检查。修正后的代码如下:

class function TJPEGImage.CanLoadFromStream(Stream: TStream): Boolean;
var
  soi, marker: Word;
  P: Int64;
begin
  P := Stream.Position;
  try
    Result := (Stream.Read(soi, SizeOf(soi)) = SizeOf(soi)) and (soi = $D8FF);
  finally
    Stream.Position := P;
  end;
end;

分享到: