IMG-LOGO
공지사항 :

PHP 이미지 다루기

lmkfox - 2025-08-06 06:22:42 10 Views 0 Comment

1. GD 라이브러리란?

GD는 이미지 생성과 조작을 위한 PHP 확장 기능입니다.

이미지 생성, 처리, 저장 등을 할 수 있고, PHP 대부분 환경에 기본 설치되어 있습니다.

php -m | grep gd  // 설치 여부 확인

설치가 안 된 경우 (Linux 기준):

sudo apt install php-gd
sudo service apache2 restart


2. 이미지 업로드 기본 예시

if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $tmpName = $_FILES['image']['tmp_name'];
    $saveName = 'uploads/' . basename($_FILES['image']['name']);
    move_uploaded_file($tmpName, $saveName);
    echo "업로드 완료";
}


3. 이미지 불러오기 (GD 사용)

GD는 이미지 형식에 따라 다른 함수를 사용합니다.

$image = imagecreatefromjpeg('path/image.jpg');    // JPEG
$image = imagecreatefrompng('path/image.png');     // PNG
$image = imagecreatefromgif('path/image.gif');     // GIF


4. 새 이미지 생성

$width = 200;
$height = 100;
$image = imagecreatetruecolor($width, $height);

// 색상 설정 (RGB)
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);

// 배경 채우기
imagefill($image, 0, 0, $white);

// 텍스트 삽입
imagestring($image, 5, 10, 10, "Hello PHP", $black);

// 이미지 출력
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);


5. 이미지 리사이즈

$src = imagecreatefromjpeg("original.jpg");
$width = imagesx($src);
$height = imagesy($src);

$newWidth = 200;
$newHeight = 200;

$dst = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

imagejpeg($dst, "resized.jpg");
imagedestroy($src);
imagedestroy($dst);


6. 이미지 자르기

$src = imagecreatefromjpeg("original.jpg");
$crop = imagecrop($src, ['x' => 100, 'y' => 50, 'width' => 200, 'height' => 200]);
if ($crop !== FALSE) {
    imagejpeg($crop, "cropped.jpg");
    imagedestroy($crop);
}
imagedestroy($src);


7. 워터마크 삽입

$base = imagecreatefromjpeg("image.jpg");
$watermark = imagecreatefrompng("watermark.png");

$bw = imagesx($base);
$bh = imagesy($base);
$ww = imagesx($watermark);
$wh = imagesy($watermark);

$destX = $bw - $ww - 10;
$destY = $bh - $wh - 10;

imagecopy($base, $watermark, $destX, $destY, 0, 0, $ww, $wh);
imagejpeg($base, "watermarked.jpg");

imagedestroy($base);
imagedestroy($watermark);


8. 이미지 형식 변환

$image = imagecreatefrompng("logo.png");
imagejpeg($image, "logo_converted.jpg", 90); // 품질 90%
imagedestroy($image);


9. 이미지 텍스트 삽입 (TrueType)

$image = imagecreatefromjpeg("background.jpg");
$black = imagecolorallocate($image, 0, 0, 0);
$font = "arial.ttf";

imagettftext($image, 20, 0, 50, 100, $black, $font, "텍스트 삽입 예시");
imagejpeg($image, "texted.jpg");
imagedestroy($image);
arial.ttf 파일은 같은 경로에 있어야 합니다.


10. 브라우저에 이미지 바로 출력

header("Content-Type: image/jpeg");
$image = imagecreatefromjpeg("photo.jpg");
imagejpeg($image);
imagedestroy($image);


11. 썸네일 자동 생성 함수 예시

function createThumbnail($srcPath, $destPath, $thumbWidth) {
    $srcImage = imagecreatefromjpeg($srcPath);
    $width = imagesx($srcImage);
    $height = imagesy($srcImage);

    $thumbHeight = floor($height * ($thumbWidth / $width));
    $thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
    imagecopyresampled($thumbImage, $srcImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);

    imagejpeg($thumbImage, $destPath);
    imagedestroy($srcImage);
    imagedestroy($thumbImage);
}


12. 이미지 처리 주의사항

  • PHP memory_limit 설정을 초과하면 오류 발생

  • 업로드된 파일의 MIME 타입 검사 필요 (exif_imagetype() 또는 finfo_file())

  • 이미지 조작 후에는 반드시 imagedestroy()로 메모리 해제

  • 웹에 출력할 땐 header() 함수로 Content-Type 지정 필요


관련 함수 정리

함수

설명

imagecreatefromjpeg()

JPEG 이미지 불러오기

imagecreatetruecolor()

빈 이미지 생성

imagecopyresampled()

리사이즈 복사

imagecrop()

이미지 자르기

imagestring()

텍스트 그리기

imagettftext()

TrueType 텍스트 삽입

imagejpeg() / imagepng()

이미지 저장 또는 출력

imagecolorallocate()

색상 정의

imagedestroy()

이미지 리소스 해제


PHP로 이미지 업로드, 처리, 출력, 보안 검사까지 모두 구현할 수 있으며, 필요 시 Imagick(Imagemagick) 같은 외부 확장도 활용할 수 있습니다.


댓글