feat: 이미지 업로드를 압축 후 순차 전송 방식으로 전환
This commit is contained in:
1 parent
c4c46db0d9
commit
23938871b0
8 files changed
+459
-25
No files matched your search
@@ -0,0 +1,249 @@
|
||||
export const MAX_UPLOAD_IMAGE_BYTES = 2 * 1024 * 1024;
|
||||
export const MAX_UPLOAD_IMAGE_DIMENSION = 2048;
|
||||
export const MAX_FALLBACK_UPLOAD_IMAGE_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
const OUTPUT_MIME_TYPE = 'image/jpeg';
|
||||
const OUTPUT_EXTENSION = 'jpg';
|
||||
const BACKEND_IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'webp', 'heic', 'heif']);
|
||||
const BACKEND_IMAGE_MIME_TYPES = new Set([
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/webp',
|
||||
'image/heic',
|
||||
'image/heif',
|
||||
'image/heic-sequence',
|
||||
'image/heif-sequence',
|
||||
]);
|
||||
|
||||
interface ImageDimensions {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
interface DecodedImage extends ImageDimensions {
|
||||
source: CanvasImageSource;
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
interface CompressionAttempt {
|
||||
scale: number;
|
||||
quality: number;
|
||||
}
|
||||
|
||||
const COMPRESSION_ATTEMPTS: CompressionAttempt[] = [
|
||||
{ scale: 1, quality: 0.86 },
|
||||
{ scale: 1, quality: 0.74 },
|
||||
{ scale: 1, quality: 0.62 },
|
||||
{ scale: 1, quality: 0.5 },
|
||||
{ scale: 0.85, quality: 0.7 },
|
||||
{ scale: 0.7, quality: 0.65 },
|
||||
{ scale: 0.55, quality: 0.6 },
|
||||
{ scale: 0.4, quality: 0.55 },
|
||||
];
|
||||
|
||||
export function calculateTargetDimensions(
|
||||
width: number,
|
||||
height: number,
|
||||
maxDimension = MAX_UPLOAD_IMAGE_DIMENSION
|
||||
): ImageDimensions {
|
||||
if (
|
||||
!Number.isFinite(width) ||
|
||||
!Number.isFinite(height) ||
|
||||
!Number.isFinite(maxDimension) ||
|
||||
width <= 0 ||
|
||||
height <= 0 ||
|
||||
maxDimension <= 0
|
||||
) {
|
||||
throw new Error('Image dimensions must be positive finite numbers.');
|
||||
}
|
||||
|
||||
const scale = Math.min(1, maxDimension / Math.max(width, height));
|
||||
|
||||
return {
|
||||
width: Math.max(1, Math.round(width * scale)),
|
||||
height: Math.max(1, Math.round(height * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
export function shouldCompressImage(
|
||||
fileSize: number,
|
||||
dimensions: ImageDimensions,
|
||||
maxBytes = MAX_UPLOAD_IMAGE_BYTES,
|
||||
maxDimension = MAX_UPLOAD_IMAGE_DIMENSION
|
||||
): boolean {
|
||||
return (
|
||||
fileSize > maxBytes ||
|
||||
dimensions.width > maxDimension ||
|
||||
dimensions.height > maxDimension
|
||||
);
|
||||
}
|
||||
|
||||
export function buildCompressedFileName(fileName: string): string {
|
||||
const extensionIndex = fileName.lastIndexOf('.');
|
||||
const baseName = extensionIndex > 0 ? fileName.slice(0, extensionIndex) : fileName;
|
||||
return `${baseName || 'image'}.${OUTPUT_EXTENSION}`;
|
||||
}
|
||||
|
||||
function getFileExtension(fileName: string): string {
|
||||
const extensionIndex = fileName.lastIndexOf('.');
|
||||
return extensionIndex >= 0 ? fileName.slice(extensionIndex + 1).toLowerCase() : '';
|
||||
}
|
||||
|
||||
export function isImageInputFile(file: Pick<File, 'name' | 'type'>): boolean {
|
||||
return file.type.startsWith('image/') || BACKEND_IMAGE_EXTENSIONS.has(getFileExtension(file.name));
|
||||
}
|
||||
|
||||
export function canUploadOriginalImage(file: Pick<File, 'name' | 'type'>): boolean {
|
||||
const hasAllowedExtension = BACKEND_IMAGE_EXTENSIONS.has(getFileExtension(file.name));
|
||||
const hasAllowedMimeType = file.type === '' || BACKEND_IMAGE_MIME_TYPES.has(file.type.toLowerCase());
|
||||
return hasAllowedExtension && hasAllowedMimeType;
|
||||
}
|
||||
|
||||
export function canUploadOriginalAfterCompressionFailure(
|
||||
fileSize: number,
|
||||
maxBytes = MAX_FALLBACK_UPLOAD_IMAGE_BYTES
|
||||
): boolean {
|
||||
return fileSize <= maxBytes;
|
||||
}
|
||||
|
||||
function useOriginalOrThrow(file: File, cause: unknown): File {
|
||||
if (!canUploadOriginalImage(file)) {
|
||||
throw new Error(
|
||||
`${file.name} 파일을 지원하는 이미지 형식으로 변환할 수 없습니다. ` +
|
||||
'JPEG, PNG 또는 WebP로 변환한 뒤 다시 시도해주세요.',
|
||||
{ cause }
|
||||
);
|
||||
}
|
||||
|
||||
if (!canUploadOriginalAfterCompressionFailure(file.size)) {
|
||||
throw new Error(
|
||||
`${file.name} 파일은 15 MB보다 크고 브라우저에서 크기를 줄일 수 없습니다. ` +
|
||||
'JPEG나 PNG로 변환하거나 더 작은 이미지를 선택해주세요.',
|
||||
{ cause }
|
||||
);
|
||||
}
|
||||
|
||||
console.warn(`Image compression was unavailable for ${file.name}; uploading the original.`, cause);
|
||||
return file;
|
||||
}
|
||||
|
||||
function decodeWithImageElement(file: File): Promise<DecodedImage> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const objectUrl = URL.createObjectURL(file);
|
||||
const image = new Image();
|
||||
|
||||
image.onload = () => {
|
||||
resolve({
|
||||
source: image,
|
||||
width: image.naturalWidth,
|
||||
height: image.naturalHeight,
|
||||
dispose: () => URL.revokeObjectURL(objectUrl),
|
||||
});
|
||||
};
|
||||
image.onerror = () => {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
reject(new Error(`Unable to decode image: ${file.name}`));
|
||||
};
|
||||
image.src = objectUrl;
|
||||
});
|
||||
}
|
||||
|
||||
async function decodeImage(file: File): Promise<DecodedImage> {
|
||||
if (typeof createImageBitmap === 'function') {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
return {
|
||||
source: bitmap,
|
||||
width: bitmap.width,
|
||||
height: bitmap.height,
|
||||
dispose: () => bitmap.close(),
|
||||
};
|
||||
}
|
||||
|
||||
return decodeWithImageElement(file);
|
||||
}
|
||||
|
||||
function canvasToBlob(canvas: HTMLCanvasElement, quality: number): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (blob) {
|
||||
resolve(blob);
|
||||
} else {
|
||||
reject(new Error('The browser could not compress the image.'));
|
||||
}
|
||||
},
|
||||
OUTPUT_MIME_TYPE,
|
||||
quality
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function compressImageForUpload(file: File): Promise<File> {
|
||||
if (!isImageInputFile(file)) {
|
||||
throw new Error(`지원하지 않는 이미지 파일입니다: ${file.name}`);
|
||||
}
|
||||
|
||||
let decoded: DecodedImage;
|
||||
try {
|
||||
decoded = await decodeImage(file);
|
||||
} catch (error) {
|
||||
return useOriginalOrThrow(file, error);
|
||||
}
|
||||
|
||||
try {
|
||||
if (
|
||||
canUploadOriginalImage(file) &&
|
||||
!shouldCompressImage(file.size, {
|
||||
width: decoded.width,
|
||||
height: decoded.height,
|
||||
})
|
||||
) {
|
||||
return file;
|
||||
}
|
||||
|
||||
const baseDimensions = calculateTargetDimensions(decoded.width, decoded.height);
|
||||
let smallestBlob: Blob | null = null;
|
||||
|
||||
try {
|
||||
const canvas = document.createElement('canvas');
|
||||
const context = canvas.getContext('2d');
|
||||
|
||||
if (!context) {
|
||||
throw new Error('The browser does not support image compression.');
|
||||
}
|
||||
|
||||
for (const attempt of COMPRESSION_ATTEMPTS) {
|
||||
canvas.width = Math.max(1, Math.round(baseDimensions.width * attempt.scale));
|
||||
canvas.height = Math.max(1, Math.round(baseDimensions.height * attempt.scale));
|
||||
|
||||
// JPEG has no alpha channel. A white background avoids transparent pixels
|
||||
// becoming black when PNG/WebP images are converted.
|
||||
context.fillStyle = '#ffffff';
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
context.drawImage(decoded.source, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
const blob = await canvasToBlob(canvas, attempt.quality);
|
||||
if (!smallestBlob || blob.size < smallestBlob.size) {
|
||||
smallestBlob = blob;
|
||||
}
|
||||
|
||||
if (blob.size <= MAX_UPLOAD_IMAGE_BYTES) {
|
||||
return new File([blob], buildCompressedFileName(file.name), {
|
||||
type: blob.type || OUTPUT_MIME_TYPE,
|
||||
lastModified: file.lastModified,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
return useOriginalOrThrow(file, error);
|
||||
}
|
||||
|
||||
const measuredSize = smallestBlob?.size ?? file.size;
|
||||
throw new Error(
|
||||
`${file.name} 파일을 ${Math.round(MAX_UPLOAD_IMAGE_BYTES / (1024 * 1024))} MB 이하로 ` +
|
||||
`압축할 수 없습니다(압축 결과: ${Math.ceil(measuredSize / (1024 * 1024))} MB).`
|
||||
);
|
||||
} finally {
|
||||
decoded.dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user