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); });

猜你喜欢

转载自www.cnblogs.com/time-is-life/p/9099316.html