您好,欢迎来到尚车旅游网。
搜索
您的当前位置:首页js如何实现将上传图片并且压缩的方法

js如何实现将上传图片并且压缩的方法

来源:尚车旅游网

这篇文章给大家介绍的内容是关于js上传图片压缩,有着一定的参考价值,有需要的朋友可以参考一下。

js实现图片压缩后上传

用到的技术:

  1. canvas相关api

  2. html5的一些api

兼容性:

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

实现思路:

  • 监听文件域的上传,通过FileReader api获取到图片的原始数据

  • 计算压缩后的宽高,然后通过画到canvas上在截取出压缩后的数据

  • <!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>

    Copyright © 2019- sceh.cn 版权所有 湘ICP备2023017654号-4

    违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

    本站由北京市万商天勤律师事务所王兴未律师提供法律服务