티스토리 뷰

반응형

프로그래밍 하다 보면, 이미지 파일의 크기를 축소해서 서버에 업로드 해야 하는 경우가 많습니다.

 

특히, 썸네일을 만들어야 할 경우 반드시 축소를 해야 합니다.

아래 함수는 실제 적용해서 사용중인 함수입니다만 보장은 할 수 없습니다.

 

필요하신 분은 복사해서 활용하여 보시고, 보완해야 할 부분이 있으면 댓글을 올려 주시면 감사합니다.

 

 


[ 필수 uses 절 ]

Graphics, Imaging, GraphUtil

 

[ 함수 정의 ]

// 사이즈 조정
// aSourceImageFile : 원본파일명
// aResultPngFile : 축소파일명
// ThumbnailSize : 축소사이즈
function ResizeImageFile(aSourceImageFile, aResultPngFile: String; ThumbnailSize: Integer): Boolean;

// 파일사이즈 구하기
function FileSize(FileName: string): Int64;

[ 함수 본문 ]

//
// Picture 리사이징.  가로MAX = ThumbnailSize.
// aSourceImageFile : 소스 파일명
// aResultPngFile : 리사이즈 파일명
// ThumbnailSize : 조정 가로 사이즈
// 성공여부 반환값 
function ResizeImageFile(aSourceImageFile, aResultPngFile: String; ThumbnailSize: Integer): Boolean;
var
  ImageExt: string;
  graphicSource: TGraphic;
  bmpSource: TBitmap;
  pngThumbnail: TPngObject;
  bmpThumbmail: TBitmap;
  fScale: Double;
begin
  Result := False;

  if not FileExists(aSourceImageFile) then
  begin
    ShowMessage(aSourceImageFile + ' 파일이 존재하지 않습니다.');
    exit;
  end;

  ImageExt := lowercase(ExtractFileExt(aSourceImageFile));
  if (ImageExt = '.jpg') or (ImageExt = '.jpeg') then
    graphicSource := TJpegImage.Create
  else if ImageExt = '.png' then
    graphicSource := TPngObject.Create
  else if ImageExt = '.gif' then
    graphicSource := TGIFImage.Create
  else if ImageExt = '.bmp' then
    graphicSource := TBitmap.Create
  else
    exit;

  pngThumbnail := TPngObject.Create;
  bmpThumbmail := TBitmap.Create;

  try
    graphicSource.Loadfromfile(aSourceImageFile);

    if ImageExt = '.bmp' then
      bmpSource := TBitmap(graphicSource)
    else
    begin
      bmpSource := TBitmap.Create;
      bmpSource.Assign(graphicSource);
    end;

    // 축소할 필요가 없을경우 나감
    if (ThumbnailSize >= bmpSource.Height) and (ThumbnailSize >= bmpSource.Width) then
    begin
      pngThumbnail.Assign(bmpSource);
      pngThumbnail.SaveToFile(aResultPngFile);
      Result := True;
      exit;
    end;

    if bmpSource.Width >= bmpSource.Height then
      fScale := ThumbnailSize / bmpSource.Width
    else
      fScale := ThumbnailSize / bmpSource.Height;



    // GraphUtil
    ScaleImage(bmpSource, bmpThumbmail, fScale);

    pngThumbnail.Assign(bmpThumbmail);
    pngThumbnail.SaveToFile(aResultPngFile);

    Result := True;
  finally
    if graphicSource <> bmpSource then
      bmpSource.Free;

    graphicSource.Free;
    pngThumbnail.Free;
    bmpThumbmail.Free;
  end;

end;

 

[ 함수 본문 ]

//
// 파일사이즈 구하기
// FileName 대상파일명
// 반환값 : 파일사이즈
function FileSize(FileName: string): Int64;
var
  sr: TSearchRec;
begin

  if FindFirst(FileName, faAnyFile, sr) = 0 then
    Result := Int64(sr.FindData.nFileSizeHigh) shl 32 + Int64(sr.FindData.nFileSizeLow)
  else
    Result := 0;

  FindClose(sr);

end;

 

반응형
댓글