Preview image upload transfer compressed and transferred base64 Detailed (dShowImg64.js)

hello, Hello, everyone, the game began, welcome to watch explain this issue. The content is uploaded a preview of the picture. Finally send the link source.
Ado, first on the map.
Style image to be uploadedThe image to be uploaded

Click on the blue box, pc can select a file, select the mobile end camera or select pictures to upload.

  • HTML part
<div class="img-box">
    <div class="card-box">
        <div class="default-box" >
            <img class="default-img" src="./cardFactory.png" alt="">
            <div class="default-title">请点击</div>
            <img class="add-img" src="./add.png" alt="">
        </div>
        <div class="up-img" id="upImg"></div>
        <input type="file" id="addImg"  class="upImg-btn">
    </div>
</div>

This layer is .default-box plus image
up-img of the image is a local post-transcoding.
The following input is selected image areas.

  • css
        .img-box {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .card-box {
            width: 7.5rem;
            height: 4rem;
            border: solid .04rem #23a7fe;
            border-radius: 4px;
            box-sizing: border-box;
            position: relative;
        }
        .upImg-btn {
            width: 100%;
            height: 100%;
            opacity: 0;
            position: absolute;
            top: 0;
            left: 0;
        }
        .up-img {
            width: 5.58rem;
            height: 3.12rem;
            margin: .2rem .6rem;
            position: absolute;
            top: .2rem;
            left: 0;
            background-repeat: no-repeat;
            background-position: center center;
            background-size: cover
        }
        .default-box {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
        }
        .add-img {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -.64rem;
            margin-top: -.64rem;
            width: 1.28rem;
            height: 1.28rem;
        }
        .default-img {
            position: absolute;
            padding: 0 1.1rem;
            bottom: .68rem;
            box-sizing: border-box;
            width: 100%;
            opacity: .5;
        }
        .default-title {
            position: absolute;
            width: 100%;
            bottom: .12rem;
            text-align: center;
            color: #23a7fe;
            font-size: .32rem;
        }

Inside is positioned.

  • Js page
    document.querySelector("#addImg").addEventListener("change",function () {
        changeImg({
            id:"addImg",           //input的Id   必须
            imgBox:'upImg',        //显示位置Id   必须
            limitType:['jpg','png','jpeg'],   //支持的类型   必须
            limitSize:819200          //图片超过多大开始进行压缩    可不传
        });
    });

We monitor input of the change of time and pass parameters

  • dShowImg64.js Code
     //id,limitType,limitSize
    function changeImg(obj = {}) {                          
        if(!obj.id) return;
        if(!obj.limitType)return;
        var dom = document.querySelector("#"+obj.imgBox);
        var files =  document.querySelector("#"+obj.id).files[0];
        var reader = new FileReader();
        var type = files.type && files.type.split('/')[1];           //文件的类型,判断是否是图片
        var size = files.size;         //文件的大小,判断图片的大小
        if (obj.limitType.indexOf(type) == -1) {
            alert('不符合上传要求');
            return;
        }
        //判断是否传入限制大小。压不压缩。
        var limitSize = obj.limitSize ? parseInt(obj.limitSize) : 0;
        if (size < limitSize) {
            reader.readAsDataURL(files);              // 不压缩,直接转base64
            reader.onloadend = function () {
                dom.style.backgroundImage = "url("+this.result+")";
                //如果要上传的话,在这里调用ajax
                document.querySelector(".default-box").style.display = "none";
            }
        } else {                                     //压缩
            var imageUrl = this.getObjectURL(files);      //创造url
            this.convertImg(imageUrl, function (base64Img) {   //调用压缩函数
                dom.style.backgroundImage = "url("+base64Img+")";
                //如果要上传的话,在这里调用ajax
                document.querySelector(".default-box").style.display = "none";
            }, type)
        }
    }
    function convertImg(url, callback, outputFormat) {
        var canvas = document.createElement('CANVAS');  //绘制canvas
        var ctx = canvas.getContext('2d');
        var img = new Image;            //初始化图片
        img.crossOrigin = 'Anonymous';
        img.onload = function () {
            var width = img.width;
            var height = img.height;
            // 按比例压缩2倍       //设置压缩比例,最后的值越大压缩越高
            var rate = (width < height ? width / height : height / width) / 2;
            canvas.width = width * rate;
            canvas.height = height * rate;           //绘制新图
            ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);                                               //转base64
            var dataURL = canvas.toDataURL(outputFormat || 'image/png');
            callback.call(this, dataURL);   //回调函数传入base64的值
            canvas = null;
        };
        img.src = url;
    }
    function getObjectURL(file) {     //创造指向该图的URL
        var url = null;
        if (window.createObjectURL != undefined) {  //大部分执行这个
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) {       // 兼容
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // 兼容
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }

First acquired various properties such as type, size,
determines whether the image size smaller than the limit, then directly to base64 less than, greater than the value, then performing reduction using canvas complete compression of revolutions and the resulting base64 background FIG. Then hide add style.

image description
The final image preview

git Address: HTTPS: //github.com/Zhoujiando ...
the future will add more widgets. Finally, I wish you all good health, thank you.

Guess you like

Origin www.cnblogs.com/homehtml/p/11828054.html