关于js图片压缩问题

2 篇文章 0 订阅
2 篇文章 0 订阅

js图片压缩

HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head></head>
<style>
    * {
        padding: 0;
        margin: 0 atuo;
    }

    .top {
        height: 300px;
        width: 1000px;
        display: flex;
        justify-content: space-between;
    }

    .left {
        text-align: center;
        width: 400px;
        height: 300px;
        border: 1px dashed #cccccc;
        background: #efefef;
    }

    .right {
        width: 590px;
        height: 300px;
        border: 1px dashed #cccccc;
        background: white;
    }

    #imgDiv {
        width: 100vw;
        height: 100vh;
    }

    #imgDiv img {
        width: 10vw;
        height: 10vh;
    }
</style>
<body>
<div class="top">
    <div class="left">
        <form method="get" enctype="multipart/form-data"><img src="../images/mgreen.jpg"/>
            <label for="inputFile" class="button">
                <div style="line-height: 40px; margin: auto; width: 200px;height: 40px;color: #FFFFFF;background: #00B7EF;border: none;border-radius: 3px;">
                    点击选择文件
                </div>
            </label>
            <input type="file" id="inputFile" style="display: none; " multiple="multiple"></form>

    </div>
    <div class="right"></div>
</div>
<div style="width: 998px;height: 45px; background: #FFFFFF;border: 1px solid #CCCCCC;line-height: 45px;">
    <span id="wenjian">选中0张文件  共0KB</span>
    <label for="inputFile" class="button">
        <span style="line-height: 40px; text-align: center; width: 100px;height: 40px; background: white;border: 1px solid #CCCCCC;border-radius: 3px;display: inline-block;">继续选择</span>
    </label>
    <input type="file" id="inputFile" style="display: none; " multiple="multiple">
    <button style="border:none;background:#00B7EF ;color: white;width: 100px;height: 35px;" onclick="sub()">开始上传
    </button>
</div>
<div id="imgDiv">
    <img id="output"/>
</div>

<script th:src="@{/js/warehouse/returnReceipt/imageConversion.js?v=1}"></script>
<script th:src="@{/lib/jquery-3.3.1/jquery.min.js}"></script>
</body>
</html>

简单压缩

function imgChange(e){ // 这里e传的是input[type=file]的this
        //检查是否有文件被选中
        if (e.files.length != 0) {
            var file = e.files[0],
                fileType = file.type,
                reader = new FileReader();
            if (!reader) {
                e.value = '';
                return;
            };
            var size = file.size;
            reader.onload = function(e) {
                //读取成功,显示到页面并发送到服务器
                e.value = '';
                var org_img = e.target.result;
                var image_base64 = org_img;
                if(size>1024*1024){ //>1M的
                    var img = new Image();
                    img.src = org_img;
                    img.onload=function(){
                        var scale = 1;
                        if(this.width > 300 || this.height > 300){
                            if(this.width > this.height){
                                scale = 300 / this.width;
                            }else{
                                scale = 300 / this.height;
                            }
                        }
                        var canvas = document.createElement("canvas"), drawer = canvas.getContext("2d");
                        if(scale!=1) {//按最大高度等比缩放
                            img.width *= scale;
                            img.height *= scale;
                        }
                        canvas.width = img.width;
                        canvas.height = img.width * (img.height / img.width);
                        drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
                        // 转为base64
                        var tmp_code = image_base64 = canvas.toDataURL(fileType);
                        if(tmp_code!='data:,'){
                            image_base64 = tmp_code;
                        }
                        img_send(image_base64);
                    };

                }else{
                    img_send(image_base64);
                }

            };
            reader.readAsDataURL(file);
        }
    }
    /**
     *为将图片赋值给消息
     **/
    function img_send(image_base64){
        const indexBase64 = image_base64.indexOf('base64,');
        if (indexBase64 < 0) return -1;
        const str = image_base64.substr(indexBase64 + 6);
        // var tag="base64,",baseStr = image_base64;
        // baseStr=baseStr.substring(baseStr.indexOf(tag)+tag.length);
        // var eqTagIndex=baseStr.indexOf("=");
        // baseStr=eqTagIndex!=-1?baseStr.substring(0,eqTagIndex):baseStr;
        // var strLen=baseStr.length;
        // var fileSize=strLen-(strLen/8)*2;
        // alert("文件大小:"+fileSize);

        console.log("base64 size is ",str.length * 0.75/1024);
        if(image_base64!='data:,'){
            document.getElementById('output').src = image_base64;
        }
    }

util.js压缩

util.js文件

// util.js
/**
 * 简易图片压缩方法
 * @param {Object} options 相关参数
 */
(function (win) {
    var REGEXP_IMAGE_TYPE = /^image\//;
    var util = {};
    var defaultOptions = {
        file: null,
        quality: 0.8
    };
    var isFunc = function (fn) { return typeof fn === 'function'; };
    var isImageType = function (value) { return REGEXP_IMAGE_TYPE.test(value); };

    /**
     * 简易图片压缩构造函数
     * @param {Object} options 相关参数
     */
    function SimpleImageCompressor(options) {
        options = Object.assign({}, defaultOptions, options);
        this.options = options;
        this.file = options.file;
        this.init();
    }

    var _proto = SimpleImageCompressor.prototype;
    win.SimpleImageCompressor = SimpleImageCompressor;

    /**
     * 初始化
     */
    _proto.init = function init() {
        var _this = this;
        var file = this.file;
        var options = this.options;

        if (!file || !isImageType(file.type)) {
            console.error('请上传图片文件!');
            return;
        }

        if (!isImageType(options.mimeType)) {
            options.mimeType = file.type;
        }

        file2Image(file, function (img) {
            var canvas = image2Canvas(img);
            file.width = img.naturalWidth;
            file.height = img.naturalHeight;
            _this.beforeCompress(file, canvas);

            canvas2Blob(canvas, function (blob) {
                blob.width = canvas.width;
                blob.height = canvas.height;
                options.success && options.success(blob);
            }, options.quality, options.mimeType)
        })
    }

    /**
     * 压缩之前,读取图片之后钩子函数
     */
    _proto.beforeCompress = function beforeCompress() {
        if (isFunc(this.options.beforeCompress)) {
            this.options.beforeCompress(this.file);
        }
    }

    // `util` 公用方法定义
    function canvas2Blob(canvas, callback, quality, type){
        canvas.toBlob(function(blob) {
            callback(blob);
        }, type || 'image/jpeg', quality || 0.8);
    }

    function file2Image(file, callback) {
        var image = new Image();
        var URL = window.webkitURL || window.URL;
        if (URL) {
            var url = URL.createObjectURL(file);
            image.onload = function() {
                callback(image);
                URL.revokeObjectURL(url);
            };
            image.src = url;
        } else {
            inputFile2DataUrl(file, function(dataUrl) {
                image.onload = function() {
                    callback(image);
                }
                image.src = dataUrl;
            });
        }
    }

    function image2Canvas(image) {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        canvas.width = image.naturalWidth;
        canvas.height = image.naturalHeight;
        ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        return canvas;
    }

    function file2DataUrl(file, callback) {
        var reader = new FileReader();
        reader.onload = function () {
            callback(reader.result);
        };
        reader.readAsDataURL(file);
    }

    // 将 `util` 公用方法添加到实例的静态属性上
    for (key in util) {
        if (util.hasOwnProperty(key)) {
            SimpleImageCompressor[key] = util[key];
        }
    }
})(window)

页面js的使用

var file = document.getElementById("inputFile");
file.addEventListener("change", function(event){
        imgarr = [...file.files];
        let arr = imgarr.map(v => {
            console.log(v.size,"origin size");
            return v.size
        });
        arr = arr.reduce((total, num) => {
            return total + num;
        });
        wenjian.innerText = `选中${imgarr.length}张文件 共${arr}KB`;
        // 压缩图片的方法, maxSize单位为kb
        imgFile = this.files[0];
        var options = {
            file: imgFile,
            quality: 0.6,
            mimeType: 'image/jpeg',
            // 压缩前回调
            beforeCompress: function (result) {
                console.log('压缩之前图片尺寸大小: ', result.size);
                console.log('mime 类型: ', result.type);
                // 将上传图片在页面预览
                // SimpleImageCompressor.file2DataUrl(result, function (url) {
                //   document.getElementById('origin').src = url;
                // })
            },
            // 压缩成功回调
            success: function (result) {
                console.log('压缩之后图片尺寸大小: ', result.size);
                console.log('mime 类型: ', result.type);
                console.log('压缩率: ', (result.size / imgFile.size * 100).toFixed(2) + '%');

                // 生成压缩后图片在页面展示
                file2DataUrl(result, function (url) {
                  document.getElementById('output').src = url;
                })

                // 上传到远程服务器
                // SimpleImageCompressor.upload('/upload.png', result);
            }
        };
        new SimpleImageCompressor(options);
    });
    
    function file2DataUrl(file, callback) {
        var reader = new FileReader();
        reader.onload = function () {
            callback(reader.result);
        };
        reader.readAsDataURL(file);
    }

使用工具类压缩

这里就不具体介绍了,大佬很多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值