본문 바로가기

Program/Delphi

[Delphi] Image파일을 확장자별로 불러오기

Delphi XE3 기준.

uses절에 Vcl.Imaging.jpeg, Vcl.Imaging.pngimage, Vcl.Imaging.gifimg 을 추가.



확장자별로 파일 불러오기 procedure. (*.BMP, *.JPEG, *.GIF, *.PNG)

procedure TForm1.ImageLoadTest;

var

  tempGraphic : TGraphic;

  tempFileStream : TFileStream;

  tempFirstBytes : AnsiString;


  tempFileName : string;

begin

  tempFileName := '파일명' (Ex : C:\Users\Public\Pictures\Test.jpg);


  tempFileStream := TFileStream.Create(tempFileName, fmOpenRead);


  SetLength(tempFirstBytes, 8);

  tempFileStream.Read(tempFirstBytes[1], 8);


  try

    // JPEG image

    if Copy(tempFirstBytes, 1, 2) = #$FF#$D8 then

    begin

      tempFileStream.Free;


      tempGraphic := TJPEGImage.Create;

      tempGraphic.LoadFromFile(tempFileName);


      tempGraphic.Free;

    end

    // GIF image

    else if Copy(tempFirstBytes, 1, 3) =  'GIF' then

    begin

      tempFileStream.Free;


      tempGraphic := TGIFImage.Create;

      tempGraphic.LoadFromFile(tempFileName);


      tempGraphic.Free;

    end

    // BMP image

    else if Copy(tempFirstBytes, 1, 2) = 'BM' then

    begin

      tempFileStream.Free;


      tempGraphic := TBitmap.Create;

      tempGraphic.LoadFromFile(tempFileName);


      tempGraphic.Free;

    end

    // PNG image

    else if tempFirstBytes = #137'PNG'#13#10#26#10 then

    begin

      tempFileStream.Free;


      tempGraphic := TPngImage.Create;

      tempGraphic.LoadFromFile(tempFileName);


      tempGraphic.Free;

    end

    else

    begin

      tempFileStream.Free;

    end;

  except

    on E : Exception do

    begin

      tempFileStream.Free;

      tempGraphic.Free;


      ShowMessage(E.Message);

    end;

  end;

end;