기술나눔

js를 사용하여 이미지 압축 기능 구현

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

이미지 압축은 특히 클라이언트가 이미지를 업로드할 때 많은 애플리케이션 시나리오에서 중요한 역할을 합니다. 원본 이미지의 크기가 큰 경우가 많습니다. 직접 업로드하면 대역폭 리소스가 많이 소모될 뿐만 아니라 업로드 속도가 느려져 사용자 경험에 심각한 영향을 미칠 수도 있습니다. 따라서 이미지를 서버에 업로드하기 전에 압축하는 것이 핵심 최적화 수단이 되었습니다. 압축을 통해 이미지 파일의 크기가 크게 줄어들어 업로드 속도가 빨라지고 효율성이 향상되며 사용자가 원활하고 번거로움 없는 환경을 누릴 수 있습니다. 이러한 최적화는 네트워크 상태가 좋지 않을 때 특히 중요합니다.
즉, 이미지 압축은 대용량 파일 업로드로 인해 발생하는 대역폭 압박과 시간 비용 문제를 효과적으로 해결할 수 있으며, 애플리케이션 응답 속도를 향상시키고 사용자 만족도를 높이는 효과적인 수단입니다. 이미지를 지능적으로 처리하고, 중복 데이터를 제거하고, 시각적 품질을 최대한 유지하면서 파일 크기를 크게 줄여 이미지 업로드 프로세스를 더 빠르고 효율적으로 만들어 전체 애플리케이션의 성능을 최적화합니다.

1. 효과 시연

여기에 이미지 설명을 삽입하세요.

2. 프로그램 코드

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <style>
        div {
            text-align: center;
        }

        input {
            height: 50px;
            line-height: 50px;
        }
    </style>
</head>

<body>
    <input id="file" type="file" accept="image/*">
    <div>压缩前的图片大小:<span id="beforeSize"></span>
        <p><img id="before" /></p>
    </div>
    <div>压缩后的图片大小:<span id="afterSize"></span>
        <p>
            <img id="after" />
        </p>
    </div>
    <script>
        $("#file").change(function () {
            const file = this.files[0];
            $("#before").attr("src", URL.createObjectURL(file));
            $("#before").css({
                width: '500',
                height: 'auto'
            });
            const fileSize = file.size / 1024;
            $("#beforeSize").html(fileSize.toFixed(2) + " KB");
            if (!file) return;
            compressImage(file, 1, 0.7).then(base64 => {
                $("#after").attr("src", base64);
                $("#after").css({
                    width: '500',
                    height: 'auto'
                });
                const sizeInKB = (base64.length * 3 / 4) / 1024;
                $("#afterSize").html(sizeInKB.toFixed(2) + " KB");
            });
        });

        function compressImage(file, maxWidth, quality) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = function (e) {
                    const img = new Image();
                    img.onload = function () {
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        canvas.width = img.width;
                        canvas.height = img.height;
                        ctx.drawImage(img, 0, 0);
                        resolve(canvas.toDataURL('image/jpeg', quality || 0.9));
                    };
                    img.src = e.target.result;
                };
                reader.readAsDataURL(file);
            });
        }
    </script>
</body>

</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74