1. 程式人生 > >js本地預覽圖片和轉base64

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格式的地址。這樣就不會提示瀏覽器安全許可權問題了。