안녕하세요?
오늘 SIR에 올라온 Q&A 글 중에서 마침 제가 예전에 작성해놓은 스크립트를 조금 수정하면 처리 가능한 질문이 있더군요.
쟁쟁하신 다른 회원님들에 비해 제가 실력은 많이 부족하지만 운좋게 답변 채택을 받았습니다 :)
1) 원본 이미지는 그대로 두고, 2) 원본 파일의 비율은 유지하되,
이미지를 원하는 크기로 축소/확대한 RAW 데이터를 리턴하여 출력하는 스크립트입니다.
방금 살짝 수정을 했지만 여전히 스크립트가 여러모로 지저분하고 군더더기가 많네요 ㅠㅠ
그래도 PNG와 JPG 파일을 테스트해봤는데 잘 리사이즈되니 다행이에요~!
<?php
function resize_image($file, $dst_w, $dst_h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$ratio = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($ratio-$dst_w/$dst_h)));
} else {
$height = ceil($height-($height*abs($ratio-$dst_w/$dst_h)));
}
$newwidth = $dst_w;
$newheight = $dst_h;
} else {
if ($dst_w/$dst_h > $ratio) {
$newwidth = $dst_h*$ratio;
$newheight = $dst_h;
} else {
$newheight = $dst_w/$ratio;
$newwidth = $dst_w;
}
}
$exploding = explode(".",$file);
$ext = end($exploding);
switch($ext){
case "png":
$src = imagecreatefrompng($file);
break;
case "jpeg":
case "jpg":
$src = imagecreatefromjpeg($file);
break;
case "gif":
$src = imagecreatefromgif($file);
break;
default:
$src = imagecreatefromjpeg($file);
break;
}
$result = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($result, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return array($result, $ext);
}
$img = resize_image('PATH', WIDTH, HEIGHT); // 파일경로, 폭, 높이를 입력하세요
ob_start();
switch($img[1]){
case "png":
imagepng($img[0]);
break;
case "jpeg":
case "jpg":
imagejpeg($img[0]);
break;
case "gif":
imagegif($img[0]);
break;
default:
imagejpeg($img[0]);
break;
}
$output = base64_encode(ob_get_contents());
ob_end_clean();
?>
<img src="data:image/<?php echo $img[1]; ?>;base64,<?php echo $output; ?>"/>이미지 처리 과정에서 서버의 리소스를 적지 않게 사용하겠지만, 이미지를 적절히 축소하면 트래픽 절감의 효과는 있겠네요 ^^
스크립트에서 사용된 함수는 아래 URL의 스크립트를 참조하였습니다.
그럼 즐겁고 뜻깊은 연말 되세요 ^^
여러모로 부족한 스크립트를 읽어주셔서 감사합니다~!
