특정 폴더를 돌면서(하위까지) 이미지 퀄리티 조절하고, 이미지 사이즈까지 조절하는 코드
마스터욱
0
90
0
0
2025-04-11 18:31:57
<?php
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0);
error_reporting(E_ALL);
ini_set('display_errors', 1);
function formatBytes($bytes, $precision = 2) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
return round($bytes / (1024 ** $pow), $precision) . ' ' . $units[$pow];
}
function logJS($msg) {
$safe = htmlspecialchars($msg);
echo "<script>appendLog(`$safe`);</script>n";
@ob_flush();
@flush();
}
function compressImage($file, $quality = 70, $maxWidth = 500) {
logJS("???? 압축 시도: $file");
$info = @getimagesize($file);
if (!$info) {
logJS("❌ 이미지 정보 가져오기 실패");
return false;
}
$mime = $info['mime'];
$origSize = filesize($file);
$srcImage = false;
switch ($mime) {
case 'image/jpeg':
$srcImage = @imagecreatefromjpeg($file);
break;
case 'image/png':
$srcImage = @imagecreatefrompng($file);
if (!$srcImage) {
logJS("❌ PNG 이미지 생성 실패");
return false;
}
if (function_exists('imagepalettetotruecolor') && $srcImage instanceof GdImage) {
imagepalettetotruecolor($srcImage);
}
imagealphablending($srcImage, false);
imagesavealpha($srcImage, true);
break;
case 'image/gif':
$srcImage = @imagecreatefromgif($file);
break;
case 'image/bmp':
if (!function_exists('imagecreatefrombmp')) {
logJS("❌ BMP 미지원");
return false;
}
$srcImage = @imagecreatefrombmp($file);
break;
default:
logJS("❌ 지원하지 않는 형식: $mime");
return false;
}
if (!$srcImage) {
logJS("❌ 이미지 리소스 생성 실패");
return false;
}
// Step 1: quality 압축
$tmpFile = $file . '.tmp';
if (!imagejpeg($srcImage, $tmpFile, $quality)) {
imagedestroy($srcImage);
logJS("❌ quality 압축 실패");
return false;
}
$compressedSize = filesize($tmpFile);
// Step 2: 리사이즈 필요 여부 판단
if ($info[0] > $maxWidth) {
logJS("⚠️ 가로 {$info[0]}px → {$maxWidth}px 리사이즈");
$ratio = $maxWidth / $info[0];
$newWidth = $maxWidth;
$newHeight = max(1, floor($info[1] * $ratio));
$resized = imagecreatetruecolor($newWidth, $newHeight);
if ($mime === 'image/png' || $mime === 'image/gif') {
imagealphablending($resized, false);
imagesavealpha($resized, true);
$transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
imagefill($resized, 0, 0, $transparent);
}
imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $info[0], $info[1]);
imagejpeg($resized, $tmpFile, $quality);
imagedestroy($resized);
}
imagedestroy($srcImage);
rename($tmpFile, $file);
logJS("✅ 압축 완료: $file (" . formatBytes($origSize) . " → " . formatBytes(filesize($file)) . ")");
return true;
}
function processDirectory($dir) {
logJS("???? 디렉토리 진입: $dir");
$files = @scandir($dir);
if (!$files) {
logJS("⚠️ 디렉토리 스캔 실패: $dir");
return;
}
foreach ($files as $file) {
if ($file === '.' || $file === '..') continue;
$path = "$dir/$file";
logJS("========== {$path} 시작 ==========");
if (is_dir($path)) {
processDirectory($path);
} elseif (is_file($path)) {
clearstatcache(true, $path);
if (!compressImage($path)) {
logJS("❌ 압축 실패: $path");
}
}
}
}
$root = $_SERVER['DOCUMENT_ROOT'] . '/upload/agency_logo_file';
$subDir = isset($_GET['dir']) ? $_GET['dir'] : '';
$target = rtrim($root . '/' . ltrim($subDir, '/'), '/');
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>이미지 압축기</title>
<style>
body { font-family: monospace; padding: 20px; }
#logContainer {
flex-direction: column-reverse;
gap: 4px;
max-height: 70vh;
overflow-y: auto;
background: #f9f9f9;
padding: 10px;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<form method="get">
<label>하위 경로 입력 (예: 2024/07/03): </label>
<input type="text" name="dir" value="<?= htmlspecialchars($subDir) ?>">
<button type="submit">압축 시작</button>
</form>
<hr>
<div id="logContainer"></div>
<script>
function appendLog(msg) {
const div = document.createElement('div');
div.innerHTML = msg;
document.getElementById('logContainer').prepend(div);
}
</script>
<?php
if (!empty($subDir)) {
if (is_dir($target)) {
logJS("???? 시작: $target");
processDirectory($target);
logJS("✅ 완료");
} else {
echo "<script>appendLog('❌ 유효하지 않은 디렉토리입니다: $target');</script>";
}
}
?>
</body>
</html>








