js本地预览图片和转base64

用代码说话安静



<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript">
        function getFileUrl(sourceId) {
            var url;
            if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
                url = document.getElementById(sourceId).value;
            } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
                url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
            } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
                url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
            }
            return url;
        }


        function convertImgToBase64(url, callback, outputFormat){
            var canvas = document.createElement('CANVAS'),
                    ctx = canvas.getContext('2d'),
                    img = new Image;
            img.crossOrigin = 'Anonymous';
            img.onload = function(){
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img,0,0);
                var dataURL = canvas.toDataURL(outputFormat || 'image/png');
                callback.call(this, dataURL);
                canvas = null;
            };
            img.src = url;
        }

        /*
        convertImgToBase64('http://bit.ly/18g0VNp', function(base64Img){
            // Base64DataURL
        });
        */

    </script>
</head>
<body>
<img width="100" height="100" id="myimg">
<input type="file" id="myfile" >
<input type="button" id="submit" value="提交">


<script type="text/javascript">

    (function() {
                document.querySelector("#myfile").onchange = function(){
                    console.log(this.value);
                    document.querySelector("#myimg").src = getFileUrl(this.id);

                };

                document.querySelector("#submit").onclick = function(){
                    var fsrc;
                    fsrc = getFileUrl("myfile");
                    convertImgToBase64(fsrc, function(base64Img){
                        console.log('11111111111111111');
                        //console.log(base64Img);
                        // Base64DataURL
                    });
                };
            }
    )();
</script>

</body>
</html>


上面代码保存个html文件就可以了。

值得注意的是

window.URL 是访问本地硬盘或者sd卡

window.URL.createObjectURL  是把本地地址转换成一个http格式的地址。这样就不会提示浏览器安全权限问题了。




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值