js 将图片链接转换成base64格式的简单实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/anran_1211/article/details/79217706

简单案例

<!DOCTYPE html>
<HTML>
<HEAD>
    <meta name =“viewport”content =“width = device-width”/>
    <title> jquery图片base64 </ title>
</ HEAD>
<BODY>
    <img src =“”id =“oImg”>  // src =转编码后的base64格式  
    <SCRIPT>
        函数convertImgToBase64(url,callback,outputFormat){  //封装函数,传入参数第一个:图片的地址,第二个:转编码后的base64格式,第三个:可以不传 
            var canvas = document.createElement ('canvas'), //创建画布  
                ctx = canvas.getContext('2d'),
                img =新图片;
            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://b.hiphotos.baidu.com/lvpics/w=1000/sign=0b3d6cc5ea50352ab16121086373faf2/8435e5dde71190ef4708f1adcd1b9d16fcfa60d4.jpg',function(base64Img){
            的console.log(base64Img);  //编码后的 
            document.getElementsByTagName('img')[0] .src = base64Img;
        });
    </ SCRIPT>
    </ BODY>
</ HTML>


展开阅读全文

没有更多推荐了,返回首页