56行JS代码轻松解决图片压缩

56行JS代码轻松解决图片压缩

    • 前言
    • 压缩函数 compression-image.js
    • 测试代码 index.html

前言

1、现在使用网页上传图片的场景越来越多,相机拍照的图片通常在3-5M之间,大多场景都不需要这么高分辨率的图片,图片太大可能影响上传速度,占用空间等。

压缩函数 compression-image.js

/**
 * 压缩图像函数
 * 
 * @param {Object} option 选项
 * option 选项对象属性介绍:
 * ->file:文件对象
 * ->maxWidth:图片最大宽度,默认值:1200
 * ->maxHeight:图片最大高度,默认值:1000
 * ->quality:图片质量,取值范围:0-1,默认值:0.6
 * ->error:压缩失败回调,唯一参数:e ,Error对象
 * ->callback:压缩成功回调,唯一参数:result ,属性介绍:
 * ----->file:源图片文件
 * ----->base64:压缩后的base64
 * ----->blob:压缩后的blob文件对象
 * ----->size:压缩后的文件大小,单位:byte
 * ----->type:图片类型
 */
function compressionImage(option) {
    if (!option) return;
    try {
        var file = option.file
        if (!file) throw new Error('file null')
        if (file.type.indexOf('image/') != 0) throw new Error('file type not image')
        var maxWidth = option.maxWidth || 1200
        var maxHeight = option.maxHeight || 1000
        var quality = option.quality || 0.6
        var callback = option.callback
        var reader = new FileReader();
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        var img = new Image();
        img.onload = function () {
            var originWidth = this.width;
            var originHeight = this.height;
            var targetWidth = originWidth;
            var targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                    targetHeight = maxHeight;
                    targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
            }
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            context.clearRect(0, 0, targetWidth, targetHeight);
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            canvas.toBlob(function (blob) {
                var reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = function (e) {
                    if (callback && typeof callback === 'function') callback({
                        file: file,
                        size: e.total,
                        base64: e.target.result,
                        blob: blob,
                        type: blob.type
                    })
                }
            }, file.type, quality);
        };
        reader.onload = function (e) {
            var r = e.target.result;
            img.src = r;
        };
        reader.readAsDataURL(file);
    } catch (e) {
        var error = option.error
        if (error && typeof error === 'function') error(e)
    }
}

测试代码 index.html



<html>

<head>
    <title>前端压缩title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport"
        content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <style>
        img {
            width: 100%;
            height: auto;
        }
    style>
head>


<body>
    <input id="file" type="file" accept="image/*">
    <p id="size">p>
    <img id="img">
    <script src="compression-image.js">script>
    <script type="text/javascript">
        var eleFile = document.querySelector('#file');
        eleFile.addEventListener('change', function (event) {
            file = event.target.files[0];
            compressionImage({
                file: file,
                callback: function (result) {
                    document.getElementById('size').innerText = '文件大小: ' + (result.size / 1024).toFixed(2) + ' KB\n   文件类型: ' + result.type
                    document.getElementById('img').src = URL.createObjectURL(result.blob);
                },
                error: function (e) {
                    console.error(e.message)
                }
            })
        });

    script>

body>

html>

你可能感兴趣的:(JavaScript,图片压缩,JS,HTML)