JavaScript – Convert Image to Base64 String

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" οnchange="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" οnclick="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 

  

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值