您现在的位置是:网站首页>前端技术>HTML5教程HTML5教程

HTML5教程图片压缩后再上传源码适用移动端和PC端

神夜2021-06-07 13:06:18HTML5教程3494人已围观文章来源:神夜个人博客

简介JS实现图片压缩后再上传到服务端,这样做上传图片的时候就不会卡住了,减少服务器端压力。通常手机拍照上传图片有好几M大小,通过压缩后再上传速度加快,图片也变小还不会变模糊。

DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>title>
    head>
    <body>

        将图片压缩过后再上传

        <input type="file" accept="image/*" id="file" onchange="selectimg()" name="file">

        <p>压缩后的图p>
        <p><img src="" id="imgs" alt="">p>
        <p>原图p>
        <p><img src="" id="imgs2" alt="">p>

        <script>
            function isMobile() {
                if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
                    return true;
                } else {
                    return false;
                }
            }

            /**H5图片压缩 返回base64 */
            function dealImage(pathfilecallback) {
                var img = new Image();
                img.src = path;
                img.onload = function() {
                    var that = this;
                    let imgMaxWidth = 500//图片最大宽
                    let imgMaxHeight = 500//图片最大高
                    let imgw = that.width;
                    let imgh = that.height;
                    let canvasW = imgw;
                    let canvasH = imgh;
                    if (imgw > imgh && imgw > imgMaxWidth) {
                        canvasW = imgMaxWidth;
                        canvasH = parseInt(imgMaxWidth * (imgh / imgw));
                    } else if (imgw < imgh && imgh > imgMaxHeight) {
                        canvasH = imgMaxHeight;
                        canvasW = parseInt(imgMaxHeight * (imgw / imgh));
                    } else if (imgw == imgh && imgw > imgMaxWidth) {
                        canvasW = imgMaxWidth;
                        canvasH = imgMaxWidth;
                    }
                    //生成canvas
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    canvas.width = canvasW;
                    canvas.height = canvasH;
                    ctx.drawImage(that00canvasWcanvasH);
                    var base64 = canvas.toDataURL('image/jpeg'0.8);
                    callback(base64);               
                }
            }

            function selectimg() {
                var reads = new FileReader();
                var f = document.getElementById('file').files[0];
                reads.readAsDataURL(f);
                reads.onload = function(e) {
                    document.getElementById("imgs2").src = this.result;
                    dealImage(this.resultfilefunction(res) {
                        console.log(res);
                        document.getElementById("imgs").src = res;
                    })
                }
            }
        script>

    body>
html>

站点信息

  • 建站时间:2017-10-24
  • 网站程序:Hsycms 3.0
  • 文章统计:511条
  • 微信公众号:扫描二维码,关注我们