图片的转base64编码

在实际开发的过程中由于需要在前端把本地图片转为base64格式然后上传到服务端,比如:用户修改头像

但是js不能直接将图片转为base64格式,所以有个间接的做法就是将要转换的图片放到画布上将画布转为base64 !上代码

<html>
    <head>
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <title>Hello Worldtitle>
    head>
    <body>
        <script type="text/javascript">
            var img = "http://img2.imgtn.bdimg.com/it/u=801721847,2075527161&fm=11&gp=0.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);//将画布转为base64
                return dataURL;
            }
            var image = new Image();//图片
            image.crossOrigin = '';//这句要有,否则可能失败
            image.src = img;
            image.onload = function(){
                var base64 = getBase64Image(image);
                console.log(base64);
            }
        script>
        <div >
            <h1>BASE64h1>
        div>
    body>
html>

你可能感兴趣的:(Web前端,base64,前端,图片)