zoukankan      html  css  js  c++  java
  • 单张图片在线预览+图片压缩

    该方法未测试浏览器兼容性,仅在谷歌上进行过测试。

    图片在线预览:一般思路是通过获取file上的绝对路径并将路径赋值给src实现在线预览功能,但现实中的浏览器,尤其是高版本浏览器由于用户安全性考虑,不会让开发者通过file获取到绝对路径,因此使用H5中的画板功能,将图片进行重绘后,得到base64编码的dataURL,再将这个地址赋值给src实现在线预览功能。

    图片压缩原理:将大图根据预定尺寸进行尺寸修改。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <p>
            <img src="images/186.jpg" alt="" id="imgInp">
        </p>
        <p>
            <input type="file" id="fileInp">
        </p>
    </body>
    <script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.js"></script>
    <script type="text/javascript">
        $('#fileInp').on('change',function(){
            imgPreView();
        })
        function imgPreView(){
            var f = $('#fileInp')[0].files[0];
            if(window.FileReader){
                var reader = new FileReader();
            }else {
                alert("您的设备不支持图片预览功能,如需该功能请升级您的设备!");
            }
            //对图片类型进行正则判断,imageType打印出来的信息是     image/jpeg
            var imageType  = /^image//;
            if(!imageType.test(f.type)){
                alert("请选择图片!");
                return;
            }
            var image = new Image();
         //根据宽高对图片进行处理,很有意思的逻辑,大家可以思考思考。 image.onload
    = function(){ var w = 1000; var h = 1000; var nw = this.naturalWidth; var nh = this.naturalHeight; var targetw = 0; var targeth = 0; if (nw > nh) { if (nw > w) { targetw = w; } else { targetw = nw; } targeth = nh / nw * targetw ; } else { if (nh > h) { targeth = h; } else { targeth = nh; } targetw = targeth / nh * nw; } var cvs = document.createElement('canvas'); var ctx = cvs.getContext("2d"); cvs.width = targetw; cvs.height = targeth; ctx.drawImage(image,0,0,nw,nh,0,0,cvs.width,cvs.height); var newImageData = cvs.toDataURL("image/jpeg"); //$(".userHead").val(newImageData.split("base64,")[1]); } reader.onload = function(e){ $("#imgInp").attr("src",e.target.result); image.src = e.target.result; }; reader.readAsDataURL(f); } </script> </html>
  • 相关阅读:
    Selenium(一):元素定位
    白盒测试系列(五)条件组合覆盖
    LDAP(轻型目录访问协议)
    Spring Intorduce、History and Design Philosophy
    CORS
    mysql创建用户并授权某个数据库
    Introduce Servlet 、Filter
    web.xml的简单解释以及Hello1中web.xml的简单分析
    ANNOTATION and analyse hello1.java
    Analysis of container and Injection in Java, their history and future.
  • 原文地址:https://www.cnblogs.com/xiaohualu/p/9840290.html
Copyright © 2011-2022 走看看