[PHP] 이미지 업로드 시 여러 개의 썸네일을 만드는 방법
일반적으로 썸네일은 이미지 크기를 줄이기 위해 생성됩니다. 업로드된 이미지에 썸네일을 생성하는 것은 좋은 습관입니다. 원본 이미지 대신 썸네일을 사용하면 애플리케이션 레이아웃에 이미지를 더 잘 표시할 수 있습니다. 또한 썸네일 이미지 로딩 시간도 상당히 단축됩니다.
프로그래밍을 통해 이미지를 업로드하고 크기를 조정하여 썸네일을 생성하는 기능은 많은 사용자가 궁금해 하는 부분입니다. 이러한 코드가 필요하다면 이 예제가 도움이 될 것입니다.
이 예제에서는 jQuery 폼 라이브러리를 사용하여 AJAX를 통해 이미지 바이너리 파일을 업로드합니다. AJAX 요청은 지정된 크기의 썸네일을 생성하는 PHP 코드를 호출합니다. 썸네일을 생성하기 전에 업로드된 파일의 확장자가 유효한지, 크기가 허용되는지 등을 검증합니다.
유효성 검사가 성공적으로 완료되면 여러 개의 썸네일을 생성하는 코드가 실행됩니다. 생성된 썸네일은 동적으로 생성된 대상에 저장됩니다. PHP GD 라이브러리 함수를 사용하여 썸네일 이미지를 프로그래밍 방식으로 생성합니다.
이미지 업로드 옵션 및 여러 개의 썸네일 미리보기 기능을 표시합니다.
이 페이지는 이미지 파일을 업로드할 수 있는 랜딩 페이지입니다. 이 UI 옵션을 사용하여 이미지 파일을 선택하면 AJAX 함수가 호출됩니다. 이 함수에서는 AJAX 매개변수에 지정된 대로 이미지 바이너리 파일이 PHP 파일로 전송됩니다.
이 페이지에서는 다양한 크기의 썸네일 이미지를 표시하기 위한 대상 컨테이너를 만들었습니다. 기본 파일 입력 태그는 CSS를 사용하여 선택 버튼 HTML 안에 숨겨집니다. 파일 입력 옵션에는 브라우저 수준에서 파일 형식을 제한하는 `accept` 속성이 포함되어 있습니다. 또한 PHP를 사용하여 서버 측에서 이미지 유효성 검사를 처리했습니다.
<div id="form-container">
<div id="imgContainer">
<form enctype="multipart/form-data" action="image_upload_submit.php"
method="post" name="image_upload_form" id="image_upload_form">
<div id="selectImage">
<div id="imgChange">
<span>Choose Image</span> <input type="file" accept="image/*"
name="image_file_input" id="image_file_input">
</div>
</div>
<div class="progress-bar">
<div class="percent">0%</div>
<div class="bar"></div>
</div>
</form>
</div>
<br>
<div class="img_preview" id="image-holder" style="display: none">
<img width="150" height="93" id="small-preview" src="#"
alt="small image" /> <img width="300" height="185"
id="medium-preview" src="#" alt="medium image" /> <img width="550"
height="340" id="large-preview" src="#" alt="big image" />
</div>
</div>jQuery를 사용하여 AJAX를 통해 폼을 전송하고 여러 개의 썸네일을 생성하는 방법
이 스크립트는 jQuery 폼 라이브러리를 사용하여 이미지 데이터가 포함된 폼을 PHP 엔드포인트로 전송합니다. 스크립트 내에서는 uploadProgress 콜백을 사용하여 업로드 진행 상황을 추적하고 UI에 업데이트합니다. AJAX 응답이 성공적으로 수신되면, 응답 객체에서 썸네일 경로를 추출하여 미리보기 대상에 동적으로 설정합니다.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>
<script>
$(document).on('change', '#image_file_input', function () {
var progressBar = $('.progress-bar');
var bar = $('.progress-bar .bar');
var percent = $('.progress-bar .percent');
var percentVal;
$('#image_upload_form').ajaxForm({
beforeSend: function() {
progressBar.fadeIn();
percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function(html, statusText, xhr, $form) {
obj = $.parseJSON(html);
if(obj.status){
percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
$("#small-preview").prop('src',obj.small);
$("#medium-preview").prop('src',obj.medium);
$("#large-preview").prop('src',obj.large);
$(".img_preview").show();
}
}
}).submit();
});
</script>PHP를 사용하여 여러 개의 썸네일 생성하는 방법
AJAX를 통해 폼 데이터가 전송되면, 업로드된 이미지를 처리하는 PHP 스크립트가 실행됩니다. 먼저 이미지 크기와 해상도를 검증합니다. 검증이 완료되면 썸네일 이미지가 생성됩니다.
이 예시에서는 150x93, 300x185, 550x340 크기의 썸네일 이미지 세 개를 생성했습니다. 생성된 썸네일 이미지는 동적으로 생성된 대상 폴더에 저장됩니다.
썸네일을 생성하고 해당 이미지를 저장할 폴더를 동적으로 지정하는 PHP 함수는 functions.php 파일에 정의되어 있습니다. 이 파일은 AJAX를 통해 호출되는 PHP 파일 위에 임포트됩니다. 썸네일은 PHP GD 라이브러리의 함수를 사용하여 동적으로 생성됩니다.
<?php
// function.php
function createFolder($path)
{
if (! file_exists($path)) {
mkdir($path, 0755, TRUE);
}
}
function createThumbnail($sourcePath, $targetPath, $file_type, $thumbWidth, $thumbHeight)
{
if ($file_type == "png") {
$source = imagecreatefrompng($sourcePath);
} else {
$source = imagecreatefromjpeg($sourcePath);
}
$width = imagesx($source);
$height = imagesy($source);
$tnumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($tnumbImage, $source, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
if (imagejpeg($tnumbImage, $targetPath, 90)) {
imagedestroy($tnumbImage);
imagedestroy($source);
return TRUE;
} else {
return FALSE;
}
}
?><?php
require_once('functions.php');
if(isset($_FILES['image_file_input']))
{
$output['status']=FALSE;
set_time_limit(0);
$allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" );
if ($_FILES['image_file_input']["error"] > 0) {
$output['error']= "File Error";
}
elseif (!in_array($_FILES['image_file_input']["type"], $allowedImageType)) {
$output['error']= "Invalid image format";
}
elseif (round($_FILES['image_file_input']["size"] / 1024) > 4096) {
$output['error']= "Maximum file upload size is exceeded";
} else {
$temp_path = $_FILES['image_file_input']['tmp_name'];
$file = pathinfo($_FILES['image_file_input']['name']);
$fileType = $file["extension"];
$fileName = rand(222, 888) . time() . ".$fileType";
$small_thumbnail_path = "uploads/small/";
createFolder($small_thumbnail_path);
$small_thumbnail = $small_thumbnail_path . $fileName;
$medium_thumbnail_path = "uploads/medium/";
createFolder($medium_thumbnail_path);
$medium_thumbnail = $medium_thumbnail_path . $fileName;
$large_thumbnail_path = "uploads/large/";
createFolder($large_thumbnail_path);
$large_thumbnail = $large_thumbnail_path . $fileName;
$thumb1 = createThumbnail($temp_path, $small_thumbnail,$fileType, 150, 93);
$thumb2 = createThumbnail($temp_path, $medium_thumbnail, $fileType, 300, 185);
$thumb3 = createThumbnail($temp_path, $large_thumbnail,$fileType, 550, 340);
if($thumb1 && $thumb2 && $thumb3) {
$output['status']=TRUE;
$output['small']= $small_thumbnail;
$output['medium']= $medium_thumbnail;
$output['large']= $large_thumbnail;
}
}
echo json_encode($output);
}
?>
0 댓글