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事件就不会执行.