前端压缩图片,上传前预览图片

上传前预览图片的需求是比较常见的,结合一些插件自己改了一下方便使用

#app {
    display: flex;
    flex-wrap: wrap;
}

#app .img-wrap-item {
    width: 33.33%;
    padding: 20px;
}

#app .img-wrap-item div {
    padding: 50%;
    position: relative;
    overflow: hidden;
    border-radius: 5px;
}

#app .img-wrap-item img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 5px;
    border: 1px solid #eee;
}
<div id="app">

</div>
<button class="btn btn-info" style="position: relative;">上传图片
	<input id="uploadImgIpt" multiple type="file" accept="image/*"
           style="opacity: 0;width:100%;height:100%;position:absolute;left:0;top:0;" />
</button>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
$("#uploadImgIpt").on('change', function () {
    var _this = this;
    YunViewUploadPic({
        elem: _this,
        maxsize: 500, //大于500KB时压缩
        maxHeight: 300, //最高300px 
        maxWidth: 300,
        success: function (res) {
            console.log('压缩完成:',res)
            $(_this).attr('data-file_length', $(_this).attr('data-file_length') - 1)
            $('#app').append('<div class="img-wrap-item"><div><img src="' + res.data +
                '" alt="' + res.name + '"/></div></div>')
            if ($(_this).attr('data-file_length') == "0") {
                console.log('生成图片完毕')
            }
        }
    })
});

function YunViewUploadPic(options) {
    var ratio = options.ratio || 0.8;
    var maxsize = options.maxsize || 1024;
    var maxWidth = options.maxWidth || 1200;
    var maxHeight = options.maxHeight || 1200;
    if (options.elem) {
        $(options.elem).attr('data-file_length', options.elem.files.length)
        for (var i = 0; i < options.elem.files.length; i++) {
            (function (file, file_index) {
                var file_item = file;
                var name = file_item.name;
                var Blobs = "";
                var reader = new FileReader();
                reader.readAsDataURL(file_item);
                var readImg = new Promise(function (resolve, reject) {
                    reader.onload = function (e) {
                        resolve(e);
                    };
                    reader.onerror = function (e) {
                        reject(e);
                    };
                });
                readImg.then(function (e) {
                    var result = e.target.result;

                    var loadImg = new Promise(function (resolve, reject) {
                        var image = new Image();
                        image.src = result;
                        image.onload = function (e) {
                            resolve(image);
                        };
                        image.onerror = function (e) {
                            reject(e);
                        };
                    });
                    loadImg.then(function (e) {
                        var canvas = document.createElement("canvas");
                        var context = canvas.getContext("2d");
                        console.log('图片宽高:', e.width, e.height, '最大宽高:', maxWidth,
                            maxHeight)
                        if (e.total / 1024 > maxsize || e.width > maxWidth || e.height >
                            maxHeight) {
                            var t_width = e.width > maxWidth ? maxWidth : e.width;
                            var t_height = e.height > maxHeight ? maxHeight : e.height;
                            if (t_width == maxWidth || t_height == maxHeight) {
                                if (t_width == maxWidth) {
                                    canvas.width = t_width;
                                    canvas.height = parseInt(e.height / (e.width /
                                        t_width));
                                    if (canvas.height > maxHeight) {
                                        canvas.width = parseInt(canvas.width / (canvas
                                            .height / maxHeight));
                                        canvas.height = maxHeight;
                                    }
                                } else {
                                    canvas.height = height;
                                    canvas.width = parseInt(e.width / (e.height /
                                        t_height));
                                    if (canvas.width > maxWidth) {
                                        canvas.height = parseInt(canvas.height / (canvas
                                            .width / maxWidth));
                                        canvas.width = maxWidth;
                                    }
                                }
                            } else {
                                canvas.height = e.height;
                                canvas.width = e.width;
                            }

                            context.drawImage(e, 0, 0, canvas.width, canvas.height);
                            var dataUrl = canvas.toDataURL(
                                'image/jpeg', ratio);
                            var compress_file = dataURLtoBlob(
                                dataUrl);
                            Blobs = dataUrl;
                            options.success({
                                data: Blobs,//用来img标签显示
                                size: length.size,
                                name: name,
                                dataType: 'image/jpeg',
                                index: file_index,
                                file:compress_file//blob文件用于上传
                            });
                            canvas = null;
                        } else {
                            options.success({
                                data: result,
                                size: file_item.size,
                                name: name,
                                dataType: file_item.type,
                                index: file_index,
                                file:file_item//原文件
                            });
                        }

                    }, function (e) {
                        console.log(e);
                    });

                }, function (e) {
                    console.log(e);
                });
            })(options.elem.files[i], i);
        }
    }

    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {
            type: mime
        });
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值