From: https://bytenota.com/javascript-convert-image-to-base64-string/

 

his post shows you two approaches how to convert an image to a Base64 string using JavaScript: HTML5 Canvas and FileReader.

1. Approach 1: HTML5 Canvas

example.js
function toDataURL(src, callback) {
    var image = new Image();
    image.crossOrigin = 'Anonymous';
 
    image.onload = function() {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        canvas.height = this.naturalHeight;
        canvas.width = this.naturalWidth;
        context.drawImage(this, 0, 0);
        var dataURL = canvas.toDataURL('image/jpeg');
        callback(dataURL);
    };

    image.src = src;
}

The above code we load the image into Image object, draw it to the canvas and then convert it to Base64 image data URL.

 

2.  Approach 2: FileReader

example.js
function toDataURL(src, callback) {
    var xhttp = new XMLHttpRequest();

    xhttp.onload = function() {
        var fileReader = new FileReader();
        fileReader.onloadend = function() {
            callback(fileReader.result);
        }
        fileReader.readAsDataURL(xhttp.response);
    };

    xhttp.responseType = 'blob';
    xhttp.open('GET', src, true);
    xhttp.send();
}

The above code we load the image as Blob via XMLHttpRequest, then use FileReader to convert the image to Base64 image data URL.

 

Use the function:

toDataURL('https://www.gravatar.com/avatar', function(dataURL) {
    // do something with dataURL
    console.log(dataURL);
});



但是这两种都是需要图片服务器允许跨域资源访问才可以,对于第二种方法,如果图片服务器不允许跨域资源访问, XMLHttpRequest的onload事件就不会执行.


注: 在实际的应用中,发现Canvas转换gif动图的时候只能取到第一帧,结果动图变成了静图,而FileReader方法则可以成功转换动图.下面两段代码分别用来出来本地文件和网络文件:

本地文件:
<!DOCTYPE html>
<html>
<head>
    <title>Blob To Base64</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
</head>
<body>
    <img id="showImg" />
    <input type="file" onchange="changeFile(event);" />
</body>
</html>
<script type="text/javascript">
    function changeFile(event) {
        file = event.target.files[0];
        var a = new FileReader();
        a.onload = function (e) {
            var base64Str = e.target.result;//获取base64
            //下面是测试得到的base64串能否正常使用:
            document.getElementById('showImg').src = base64Str;
        }
        a.readAsDataURL(file);
    }
</script>

网络文件:

<!DOCTYPE html>
<html>
<head>
    <title>Blob To Base64</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
</head>
<body>
    <img id="showImg" />
    <input type="button" value="Test" onclick="TestBase64();" />
</body>
</html>
<script type="text/javascript">
	
	function TestBase64()
	{
		var fileUrl = "http://29e5534ea20a8.cdn.sohucs.com/c_zoom,h_86/c_cut,x_8,y_0,w_225,h_150/os/news/e4337401e7ebeac6f7cdb52fac9807e5.gif"
		toDataURL(fileUrl, function(base64)
		{
			document.getElementById('showImg').src = base64;
		});
	}
	
	function toDataURL(src, callback) {
		var xhttp = new XMLHttpRequest();

		xhttp.onload = function() {
			var fileReader = new FileReader();
			fileReader.onloadend = function() {
				callback(fileReader.result);
			}
			fileReader.readAsDataURL(xhttp.response);
		};

		xhttp.responseType = 'blob';
		xhttp.open('GET', src, true);
		xhttp.send();
	}

</script>

  

另外找动图可以到这里面来找: https://tieba.baidu.com/p/4674320064 

  

 

 
posted on 2018-05-28 11:41  今夜太冷  阅读(959)  评论(0编辑  收藏  举报