마스터욱
Toggle navigation
  • 회원가입 | 정보찾기
ICON NAVIGATION
정보수정 쪽지함 주변맛집 익명채팅
공지사항 채팅 개발문의 방명록
  • MAIN NAVIGATION
  • 메인
  • 마스터욱 공간
    • 마스터욱 소개
    • 개발 리스트
    • 공지사항
    • 방명록
  • 마스터욱 외부자료
    • 네이버
    • 티스토리
    • 깃허브(github)
  • 개인 프로젝트
    • 랜덤 이성 채팅
    • Auto 크롤링
    • Javascript 카카오 채팅
    • 파이썬 뉴스매매
    • C# 키움 주식 자동매매
    • C# 키움 주식 패턴 분석
    • PHP 욱보드
    • 업비트 자동매매 개발
    • 업비트 자동매매 일지
  • 개발 의뢰
    • 개발 문의
    • 개발 견적
    • 개발 피드백
    • FAQ
  • 개발 경험 Tip
    • PHP
    • JSP
    • HTML
    • Javascript
    • Android
    • C#
    • MySQL
    • Linux
    • Python
    • NodeJS
    • React
    • Vue.js
    • Flutter
    • 정규식
    • 기타
  • 커뮤니티
    • 자유게시판
    • 추천사이트
    • 영화
    • 여행
    • 유머
    • Overseas News
  • 맛집&즐길 거리 탐방
    • 맛집 정보
    • 즐길 거리 정보
    • 내 주위 맛집&즐길 거리
  • 공유 사진
    • 음식
    • 여행
    • 캐릭터
    • 배경
    • 기타
    • 이모티콘
    • 일러스트
  • 놀이터
    • 블록뽀시기
    • 트레이딩뷰
    • 로또 시뮬레이션
    • 쳇쳇 익명 채팅
    • 랜덤 이성 채팅
    • AI 채팅
    • 미니 채팅
    • 바이너리 테스트
    • 마번호 생성기
    • 바카라 시뮬레이션
    • 홀짝점수 테스트
    • 로또 분석기
SITE STATISTICS
  • - 명 현재 접속자
  • 1,311 명 오늘 방문자
  • 2,215 명 어제 방문자
  • 5,192 명 최대 방문자
  • 695,113 명 전체 방문자
  • 2,570 개 전체 게시물
  • 496 개 전체 댓글수
Facebook Twitter GooglePlus KakaoStory NaverBand
  1. 홈
  2. PHP
목록으로

특정 폴더를 돌면서(하위까지) 이미지 퀄리티 조절하고, 이미지 사이즈까지 조절하는 코드

마스터욱 0 218 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>

0
0

목록

Facebook Twitter GooglePlus KakaoStory NaverBand
0 Comments

비밀번호 확인

확인
댓글은 자신을 나타내는 '얼굴'입니다. *^^*
등록
자동등록방지 숫자를 순서대로 입력하세요.

댓글수정


글쓰기
검색
번호 제목 이름 날짜 조회
  • 81
    특정 폴더를 돌면서(하위까지) 이미지 퀄리티 조절하고, 이미지 사이즈까지 조절하는 코드
    마스터욱
    조회수 219   25-04-11 18:31
    마스터욱
    25-04-11 18:31
    219
  • 80
    JSON 데이터 DB에 넣을때, 데이터를 이쁘게 해주는 함수(JSON_PRETTY_PRINT)
    마스터욱
    조회수 190   25-02-08 13:45
    마스터욱
    25-02-08 13:45
    190
  • 79
    PHP 로 웹푸시 만들기
    마스터욱
    조회수 240   23-05-11 22:16
    마스터욱
    23-05-11 22:16
    240
  • 78
    FastCGI sent in stderr: "PHP message: PHP Fatal error: Allowed memory size of
    마스터욱
    조회수 186   22-12-04 05:36
    마스터욱
    22-12-04 05:36
    186
  • 77
    window apache2 php7 에서 curl 이 인식되지 않을때 해결방법
    마스터욱
    조회수 176   22-08-08 22:41
    마스터욱
    22-08-08 22:41
    176
  • 76
    exec 사용시에 에러확인 방법
    마스터욱
    조회수 167   22-06-23 01:52
    마스터욱
    22-06-23 01:52
    167
  • 75
    리눅스(우분투) 시스템 모니터링 PHP 오픈소스
    마스터욱
    조회수 152   22-01-10 00:27
    마스터욱
    22-01-10 00:27
    152
  • 74
    json_encode 시에 한글이 깨지는 경우 해결방법
    마스터욱
    조회수 180   21-12-23 05:24
    마스터욱
    21-12-23 05:24
    180
  • 73
    exec 사용시, 에러확인 방법
    마스터욱
    조회수 150   21-12-19 16:08
    마스터욱
    21-12-19 16:08
    150
  • 72
    PHP - PDF 파일 만들기
    마스터욱
    조회수 151   21-12-16 11:23
    마스터욱
    21-12-16 11:23
    151
  • 71
    http_build_query 함수에서 배열처리
    마스터욱
    조회수 170   21-12-07 06:10
    마스터욱
    21-12-07 06:10
    170
  • 70
    http 로 접속할 경우, https 로 포워딩 되도록 하는 소스
    마스터욱
    조회수 161   21-11-16 22:57
    마스터욱
    21-11-16 22:57
    161
  • 69
    exec 함수 사용시, 백그라운드에서 명령어 실행하기
    마스터욱
    조회수 179   21-11-10 04:08
    마스터욱
    21-11-10 04:08
    179
  • 68
    크롤링 라이브러리 스누피(Snoopy) 사용시 노하우 팁!
    마스터욱
    조회수 402   21-10-20 02:24
    마스터욱
    21-10-20 02:24
    402
  • 67
    PHP 숫자 0 을 인식하는 방법
    마스터욱
    조회수 232   21-05-27 14:32
    마스터욱
    21-05-27 14:32
    232
  • 66
    텔레그램 채널 알림(푸시) API
    마스터욱
    조회수 153   21-04-08 02:05
    마스터욱
    21-04-08 02:05
    153
  • 65
    [2] apmsetup 대신에 쓸만한 프로그램, 오토셋(Autoset) [2]
    마스터욱
    조회수 179   21-04-07 16:25
    마스터욱
    21-04-07 16:25
    179
  • 64
    jQuery ezPlus 그누보드 상세페이지 이미지에 적용소스
    마스터욱
    조회수 177   21-03-22 16:34
    마스터욱
    21-03-22 16:34
    177
  • 63
    bitmex API - 주문리스트 가져오기(order list)
    마스터욱
    조회수 191   21-01-03 16:31
    마스터욱
    21-01-03 16:31
    191
  • 62
    bitmex API - 주문하기(order)
    마스터욱
    조회수 203   20-12-31 17:11
    마스터욱
    20-12-31 17:11
    203
글쓰기
검색
  • 1
  • 2
  • 3
  • …
  • 5
  • 다음

Search

개인정보처리방침
마스터욱. All rights reserved.

Close

0 명 접속중
Time Loading...