class upImageResizeUpload { constructor(limit) { this.limit = limit; this.isWidthOnly = false; this.maxSize = 0; if (typeof limit === 'string' && limit.startsWith('!')) { this.isWidthOnly = true; this.maxSize = parseInt(limit.substring(1)); } else { this.maxSize = parseInt(limit); } } handleFileChange(file_el, text_el) { text_el.value = file_el.value; const file = file_el.files[0]; if (!file) { // 사용자가 취소했거나 파일 선택 안 한 경우 file_el.value = ''; return; } if (!file.type.startsWith('image/')) { // 이미지가 아닌 경우 text_el.value += ' (' + number_format(file.size) + ' Byte)'; return; } if(this.maxSize<100){ // limit 100이하면 원본 줄임 안함 text_el.value += ' (' + number_format(file.size) + ' Byte)'; return; } // 이미지일 경우 리사이즈 처리 const reader = new FileReader(); reader.onload = (e) => { const img = new Image(); text_el.value += ' 이미지 리사이즈 중 ...'; img.onload = () => { if((this.isWidthOnly && img.width <= this.maxSize) || (!this.isWidthOnly && Math.max(img.width, img.height)<=this.maxSize)){ //console.log('리사이징 안함', file); text_el.value = file_el.value + ' → 리사이즈 불필요 (' + number_format(file.size) + ' Byte)'; return; } const [canvas, newType] = this.resizeImage(img); canvas.toBlob(blob => { const resizedFile = new File([blob], file.name, { type: newType }); // input.files 교체 const dataTransfer = new DataTransfer(); dataTransfer.items.add(resizedFile); file_el.files = dataTransfer.files; // 미리보기 등 리사이즈 후 처리 필요 시 여기에 //console.log('리사이징 완료:', resizedFile); text_el.value = file_el.value + ' → 리사이즈 완료 (' + number_format(resizedFile.size) + ' Byte)'; }, file.type, 0.8); }; img.src = e.target.result; }; reader.readAsDataURL(file); } resizeImage(img) { let width = img.width; let height = img.height; let scale = 1; if(this.isWidthOnly) { if(width > this.maxSize) { scale = this.maxSize / width; } }else { const maxDim = Math.max(width, height); if (maxDim > this.maxSize) { scale = this.maxSize / maxDim; } } const canvas = document.createElement('canvas'); canvas.width = width * scale; canvas.height = height * scale; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); return [canvas, img.type || 'image/jpeg']; } }