HTML5 Picture Compression Rotation Adjustment

Picture upload is needed in recent projects, but at present, photos taken or scanned will be very large. When uploaded directly to the server, there will be too many pictures. Files will affect the upload speed, and if the resolution of the picture is too large, it is also a problem to view. So I think of using HTML 5 Canvas technology to compress and upload pictures in the front end. However, after the compression problem has been solved, there are problems. The client usually takes pictures or scans, and the pictures need to be rotated before viewing. Therefore, it is thought that if the pictures are rotated customically first, then the pictures are compressed and uploaded.

Referring to some articles on the internet, this function has been worked out.

http://qings.blog.51cto.com/4857138/997998/

http://www.cnblogs.com/hutuzhu/p/5265023.html

http://leonshi.com/demo/canvas-compressor.html

Now let's talk about the concrete implementation method.

FileReader compresses the image to provide a preview when loading the image. Because the size of the image is not constant, the default resolution ratio of the image can be set, such as 800*1000. It is possible that the length and width of the image are less than the set value. Therefore, it is necessary to determine which proportion to convert according to the actual value of the length and width and the ratio of the set value. Picture rotation can only be done on the original map, so as to ensure that after rotation, the original map and the set value of the proportion of re-compression.

Code:

 var canvas = document.getElementById('canvas');
    var source = document.getElementById('source');
    var preview = document.getElementById('preview');

    var dataUrl;//Picture Compressed Path

    var qualityLevel = 0.8;

    $(function () {
        $('#single').on('change', function (e) {
            var img = e.target.files[0]
            var reader = new FileReader();
            reader.readAsDataURL(img);
            reader.onload = function (e) { // reader onload start
                var url = reader.result;
                source.src = url;

            } // reader onload end

            reader.readAsDataURL(img);
        })
    })

    source.onload = function () {
        var width = source.width;
        var height = source.height;
        var context = canvas.getContext('2d');

        var newwidth = 800;
        var newheight = 1000;

        canvas.width = newwidth;
        canvas.height = newheight;

        //When the width and height are less than the set value
        if (width <= newwidth && height <= newheight) {
            newwidth = width;
            newheight = height;
        }
        //When the width is less than the setting value and the height is greater than the setting value, adjust in proportion to the height.
        if (width <= newwidth && height > newheight) {
            newwidth = newheight / height * width;
        }
        //When the width is greater than the setting value and the height is less than the setting value, the ratio of width is adjusted.
        if (width > newwidth && height <= newheight) {
            newheight = newwidth / width * height;
        }
        //When the width and height are greater than the setting value
        if (width > newwidth && height > newheight) {
            var bla = newwidth / width;
            var blb = newheight / height;
            if (bla > blb) {
                newwidth = width * blb;
                newheight = height * blb
            }
            else {
                newwidth = width * bla;
                newheight = height * bla;
            }
        }


        var sx = 0;
        var sy = 0;
        var sWidth = width;
        var sHeight = height;
        var dx = 0;
        var dy = 0;
        var dWidth = newwidth;
        var dHeight = newheight;

        $("#detail").html("W:" + sWidth + " H:" + sHeight)


        context.drawImage(source, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

        dataUrl = canvas.toDataURL('image/jpeg', qualityLevel);
        //preview.src = dataUrl;
    };

    function compress(pid) {
        var source = document.getElementById("pic_" + pid);
        var width = source.width;
        var height = source.height;
        var context = canvas.getContext('2d');

        var newwidth = 800;
        var newheight = 1000;

        canvas.width = newwidth;
        canvas.height = newheight;

        //When the width and height are less than the set value
        if (width <= newwidth && height <= newheight) {
            newwidth = width;
            newheight = height;
        }
        //When the width is less than the setting value and the height is greater than the setting value, adjust in proportion to the height.
        if (width <= newwidth && height > newheight) {
            newwidth = newheight / height * width;
        }
        //When the width is greater than the setting value and the height is less than the setting value, the ratio of width is adjusted.
        if (width > newwidth && height <= newheight) {
            newheight = newwidth / width * height;
        }
        //When the width and height are greater than the setting value
        if (width > newwidth && height > newheight) {
            var bla = newwidth / width;
            var blb = newheight / height;
            if (bla > blb) {
                newwidth = width * blb;
                newheight = height * blb
            }
            else {
                newwidth = width * bla;
                newheight = height * bla;
            }
        }


        var sx = 0;
        var sy = 0;
        var sWidth = width;
        var sHeight = height;
        var dx = 0;
        var dy = 0;
        var dWidth = newwidth;
        var dHeight = newheight;

        $("#detail").html("W:" + sWidth + " H:" + sHeight)


        context.drawImage(source, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

        dataUrl = canvas.toDataURL('image/jpeg', qualityLevel);
        //preview.src = dataUrl;
    }


    var quality = document.getElementById('quality');
    quality.addEventListener('keydown', function (e) {
        if (e.which === 13) {
            var value = e.currentTarget.value;
            value = value < 1 ? 1 : value;
            value = value > 100 ? 100 : value;
            qualityLevel = parseFloat(value / 100);
            document.getElementById('level').innerText = qualityLevel;
            source.onload();
        }
    }, false);

    function rotateImg(pid, direction) {
        //Minimum and Maximum Rotation Directions. Pictures rotate four times and then return to the original direction.  
        var min_step = 0;
        var max_step = 3;
        var img = document.getElementById(pid);
        if (img == null) return;
        //The height and width of the img cannot be obtained after the img element is hidden, otherwise errors will occur.  
        var height = img.height;
        var width = img.width;
        var step = img.getAttribute('step');
        if (step == null) {
            step = min_step;
        }
        if (direction == 'right') {
            step++;
            //Rotate to the original position, i.e. exceed the maximum value  
            step > max_step && (step = min_step);
        } else {
            step--;
            step < min_step && (step = max_step);
        }
        img.setAttribute('step', step);
        var canvas = document.getElementById('pic_' + pid);
        if (canvas == null) {
            img.style.display = 'none';
            canvas = document.createElement('canvas');
            canvas.setAttribute('id', 'pic_' + pid);
            img.parentNode.appendChild(canvas);
        }
        //Rotation angle is parameterized by radian  
        var degree = step * 90 * Math.PI / 180;
        var ctx = canvas.getContext('2d');
        switch (step) {
            case 0:
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0);
                break;
            case 1:
                canvas.width = height;
                canvas.height = width;
                ctx.rotate(degree);
                ctx.drawImage(img, 0, -height);
                break;
            case 2:
                canvas.width = width;
                canvas.height = height;
                ctx.rotate(degree);
                ctx.drawImage(img, -width, -height);
                break;
            case 3:
                canvas.width = height;
                canvas.height = width;
                ctx.rotate(degree);
                ctx.drawImage(img, -width, 0);
                break;
        }
        compress('source');
    }


demo Download


Keywords: less

Added by d-woo on Thu, 20 Jun 2019 01:36:37 +0300