Home > Web Front-end > JS Tutorial > How to implement the method of uploading and compressing images in js

How to implement the method of uploading and compressing images in js

不言
Release: 2018-07-20 11:02:36
Original
1970 people have browsed it

This article introduces you to the compression of js uploaded images. It has certain reference value. Friends in need can refer to it.

js implements image compression and uploading

Technology used:

  1. canvas related api

  2. Some APIs of html5

Compatibility:

h5没发现问题,pc低版本浏览器不支持
Copy after login

Implementation ideas:

  • Monitor the upload of the file field and obtain the original data of the image through the FileReader api

  • Calculate the compressed width and height, and then draw it on the canvas Intercept the compressed data

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="file" id="file">
    <canvas id="canvas"></canvas>
</body>

</html>
<script>
    // 兼容性 h5上可以使用,pc低版本浏览器不支持
    // 准备要用到的img和canvas
    var img = new Image(),
        canvas;
    // 创建读取文件对象
    var render = new FileReader();
    // 如果不需要放在页面上,使用js创建该元素就可以了
    // canvas = document.createElement('canvas');

    // 找到canvas,准备画图
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    var input = document.getElementById('file');
    input.addEventListener('change', function (e) {
        // 通过files获取到当前文件
        var file = e.target.files[0];
        // 如果选择的是图片
        if (file.type.indexOf('image') != -1) {
            // 读取file文件,得到的结果为base64位
            render.readAsDataURL(file);
        };
    });
    render.onload = function (result) {
        // 把读取到的base64图片设置给img的src属性
        var src = render.result;
        img.src = src;
    };
    img.onload = function () {
        // 加载完毕后获取图片的原始尺寸
        var origin_width = this.width;
        var origin_height = this.height;
        // 设置最大允许宽高,根据需求自己设置,值越大,图片大小越大
        var max_width = 400;
        var max_height = 400;

        // 最终宽高
        var target_width = origin_width;
        var target_height = origin_height;
        if (origin_width > max_width || origin_height > max_height) {
            if (origin_width / origin_height > max_width / max_height) {
                // 更宽,按照宽度限定尺寸
                target_width = max_width;
                target_height = Math.round(max_width * (origin_height / origin_width));
            } else {
                target_height = max_height;
                target_width = Math.round(max_height * (origin_width / origin_height));
            }
        }
        canvas.width = target_width;
        canvas.height = target_height;
        // 绘画到画布上
        context.drawImage(img, 0, 0, target_width, target_height);
        /*
            此处得到的是blob对象,blob对象是在ie10及以上才兼容,在ios8_1_1上和iphoneSE上有兼容问题
            canvas.toBlob(function(result) {
                console.log(result);
            });
        */
        // 读取canvas的数据
        var result = canvas.toDataURL();
        // 得到的结果是base64位的字符串,拿到压缩后的值通过网络请求交给后台处理...
        // 如果是blob对象,需要通过FormData对象发送
        console.log(result);
    };

</script>
Copy after login

Related recommendations:

Algorithm analysis of the full arrangement of strings in js

Use of React: State management inside React components

The above is the detailed content of How to implement the method of uploading and compressing images in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template