JS와 Canvas로 브라우저에서 이미지 리사이즈하기


사이트에 이미지를 올릴 때 이미지를 리사이즈할 필요가 있는 경우가 있다. 이때, 브라우저에서 이미지를 리사이즈 하는 방법을 알아보자. 우선 이미지를 업로드해야 하므로 input 태그를 사용한다. 그리고 이미지를 리사이즈 하기 위해 canvas 태그를 사용한다. canvas는 사용자에게 보여질 필요가 없으므로 display: none; 으로 숨겨준다.

<input type="file" accept="image/*" id="image-upload" />
<canvas id="canvas" style="display: none;"></canvas>

이제 이벤트를 받아서 이미지를 리사이즈 하는 함수를 만들어보자.

  1. 우선 파일 인풋에서 받은 파일을 가져온다. 그리고 canvas에 그림을 그릴 수 있도록 Image 객체를 생성한다.
  2. 이미지가 로드되면 캔버스에 이미지를 그리고, toBlob 메소드를 사용하여 이미지를 Blob 형태로 변환한다.
  3. Blob 형태로 변환된 이미지를 File 객체로 변환하여 사용할 수 있다.

이 과정을 코드로 나타내면 다음과 같다.

const canvasRef = document.getElementById('canvas') as HTMLCanvasElement;

async function handleImageUpload(event: Event) {
    const file = (event.target as HTMLInputElement).files?.[0];
    if (!file) return;

    const ctx = canvasRef.getContext('2d');

    const image = new Image();
    image.src = URL.createObjectURL(file);

    image.onload = () => {
        if (!ctx) return;
        const aspectRatio = image.height / image.width;
        const newWidth = 200;
        const newHeight = newWidth * aspectRatio;

        canvasRef.width = newWidth;
        canvasRef.height = newHeight;

        ctx.imageSmoothingEnabled = true;
        ctx.imageSmoothingQuality = 'high';
        ctx.drawImage(image, 0, 0, newWidth, newHeight);

        canvasRef.toBlob(async (blob) => {
            if (!blob) return;
            const resizedFile = new File([blob], file.name, { type: file.type });
        });
    };
}

나같은 경우에는 이미지를 리사이즈 할 때, 가로 길이를 200px로 고정하고 세로 길이는 가로 길이에 맞춰 비율을 유지하도록 했다. 그리고 이미지를 Blob 형태로 변환해서 바로 S3에 업로드하는 방식으로 사용했는데, 어떻게 사용할 지는 상황에 맞게 결정하면 된다.