Image Compression in JavaScript : Image to base64 encoder
Image compression is a type of data compression applied to images, to reduce their cost for storage or transmission
Base64 is a binary-to-text encoding scheme. It represents binary data in a printable ASCII string format by translating it into a radix-64 representation. Base64 encoding is commonly used when there is a need to transmit binary data over media.
Here we are going to use Canvas approach to compress image.
function toDataURL(src, callback) {
var image = new Image(); // create Image object
image.crossOrigin = 'Anonymous';
image.onload = function() {
var canvas = document.createElement('canvas'); //initialize 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;
}
here we have created canvas of image and converted it to data-URL and passed as callback to next function which takes image URL as argument and converting it to base 64 string.
toDataURL('https://www.gravatar.com/avatar', function(dataURL) {
document.getElementById('result').innerHTML = dataURL;
// dataURL is output base64 string
});
output :
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQC
Full Code
<!DOCTYPE html>
<html>
<head>
<title>JavaScript – Convert Image to Base64 String</title>
</head>
<body>
<div>Data URL:</div>
<div id="result"></div>
<script type="text/javascript">
function toDataURL(src, callback) {
var image = new Image(); // create Image object
image.crossOrigin = 'Anonymous';
image.onload = function() {
var canvas = document.createElement('canvas'); //initialize 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;
}
toDataURL('https://www.gravatar.com/avatar', function(dataURL) {
// passed image url in function args
document.getElementById('result').innerHTML = dataURL;
// base64 string
});
</script>
</body>
</html>
So, this is how we can convert image to base64 string in javascript.