delphi编程如何判断图片文件的真实类型?

本文主要讲解了如何判断一个图片文件的真实类型,并不是从后缀名来判断类型的方法:



以下是引用片段:



unit Unit55;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls;



type

  TImageType = (IT_None, IT_Error, IT_Bmp, IT_JPEG, IT_GIF, IT_PCX, IT_PNG,

    IT_PSD, IT_RAS, IT_SGI, IT_TIFF);



  TForm55 = class(TForm)

    OpenDialog1: TOpenDialog;

    Button1: TButton;

    procedure Button1Click(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;



var

  Form55: TForm55;



implementation



{$R *.dfm}



function CheckImageType(FileName: string): TImageType;

var

  MyImage: TMemoryStream;

  Buffer: Word;

begin

  MyImage := TMemoryStream.Create;

  try

    MyImage.LoadFromFile(FileName);

    MyImage.Position := 0;

    if MyImage.Size = 0 then // 如果文件大小等于0,那么错误(

    begin

      Result := IT_Error;

      Exit;

    end;

    MyImage.ReadBuffer(Buffer, 2); //读取文件的前2个字节,放到Buffer里面



    case Buffer of

      $4D42:

        Result := IT_Bmp;

      $D8FF:

        Result := IT_JPEG;

      $4947:

        Result := IT_GIF;

      $050A:

        Result := IT_PCX;

      $5089:

        Result := IT_PNG;

      $4238:

        Result := IT_PSD;

      $A659:

        Result := IT_RAS;

      $DA01:

        Result := IT_SGI;

      $4949:

        Result := IT_TIFF;

    else

      Result := IT_None;

    end;

  finally

    MyImage.Free;

  end;

end;



procedure TForm55.Button1Click(Sender: TObject);

begin

  if not OpenDialog1.Execute then

    Exit;

  if CheckImageType(OpenDialog1.FileName)<>IT_Bmp then

    showmessage('不是BMP格式');



end;



end.



你可能感兴趣的:(Delphi)