zoukankan      html  css  js  c++  java
  • JS_图片压缩并预览

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>上传图片并预览</title>
    </head>
    <body>
    点击下方图片选择要上传的图片<br>
    <label>
        <input id="upload" type="file" style="position:absolute;opacity:0" accept="image/*" onchange="show('upload','img')">
        <img id="img" src="../static/images/upload.jpg" width="30%" height="30%" alt="图片加载失败">
    </label>
    
    <script>
        function show(fileId, imgId) {
            var file = document.getElementById(fileId).files[0];
            var imgShow = document.getElementById(imgId);
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                var imgSrc = this.result;
                if (file.size > 1 * 1024 * 1024) {
                    var img=new Image();
                    img.src=this.result;
                    img.onload=function(){
                        imgSrc= compress(img,0.3,file.type);
                        imgShow.src = imgSrc;
                    }
                }else{
                    imgShow.src = imgSrc;
                }
    
            }
        }
    
        function compress(img, quality, type) {
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');
            canvas.width = img.width/2;
            canvas.height = img.height/2;
            context.drawImage(img, 0, 0, canvas.width, canvas.height);
            var res = canvas.toDataURL(type, quality);
            return res;
        }
    </script>
    </body>
    </html>
  • 相关阅读:
    myeclise中创建maven web程序
    java定时任务调度工具
    fastjson常用方法
    log4j2的配置及使用
    spring事务配置
    java利用poi解析excel文件
    ScheduledTheadPool线程池的使用
    ThreadPoolExecutor线程池
    jQuery属性操作(一)
    jQuery队列(三)
  • 原文地址:https://www.cnblogs.com/xiangguoguo/p/9418726.html
Copyright © 2011-2022 走看看