img图片转成base64

Posted on 2019-09-27 14:34  jessie-xian  阅读(3172)  评论(0编辑  收藏  举报

方法一:canvas

 <script type="text/javascript">
        var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";
        //var img = "http://127.0.0.1/base64/1.jpg";
        function getBase64Image(img) {
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;

            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
            var dataURL = canvas.toDataURL("image/" + ext);
            return dataURL;
        }
        var image = new Image();
        image.crossOrigin = '';
        image.src = img;
        image.onload = function () {
            var base64 = getBase64Image(image);
            console.log(base64);
        }
    </script>

方法二:FileReader

<html>
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
     <title>通过filereader接口读取文件</title>
     <script type="text/javascript">
         function readAsDataURL()
         {
             if(typeof FileReader=='undifined')          //判断浏览器是否支持filereader
             {
                 result.innerHTML="<p>抱歉,你的浏览器不支持 FileReader</p>";
                 return false;
             }
             var file=document.getElementById("imagefile").files[0];
             if(!/image\/\w+/.test(file.type))           //判断获取的是否为图片文件
             {
                 alert("请确保文件为图像文件");
                 return false;
             }
             var reader=new FileReader();
             reader.readAsDataURL(file);
             reader.onload=function(e)
             {
                 var result=document.getElementById("result");
                 result.innerHTML='<img src="'+this.result+'" alt=""/>'
             }
        }
     </script>
 </head>
<body>
 <p>
     <label>请选择一个文件:</label>
     <input type="file" id="imagefile" />
     <input type="button" value="读取图像" onClick="readAsDataURL();" />
 </p>
 <div name="result" id="result">
     <!-- 这里用来显示图片结果-->
 </div>
 </body>
 </html>


参考:https://cloud.tencent.com/developer/article/1399137
https://www.cnblogs.com/tugenhua0707/p/4666076.html