js本地预览图片和转base64

来源:互联网 发布:淘宝店铺客户服务 编辑:程序博客网 时间:2024/05/17 06:55

用代码说话安静



<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 0