Learn Javascript Files and images - aliconnect/aliconnect.sdk GitHub Wiki
In this short tutorial we explore 3 different JavaScript methods to convert an image into a Base64 string. We look at converting a File object or Blob, a canvas element, and an image tag.
In all examples below we assume we already have a , , File, or Blob object available.
We’ll be converting images to DataURLs, we can use the function below to convert a DataURL to a Base64 string.
const getBase64StringFromDataURL = (dataURL) =>
dataURL.replace('data:', '').replace(/^.+,/, '');
Let’s get started.
If we have a that we want to turn into a Base64 string we can use toDataURL on the Canvas element.
<canvas width="300" height="150" id="my-canvas"></canvas>
<script>
const canvas = document.getElementById('my-canvas');
// Convert canvas to dataURL and log to console
const dataURL = canvas.toDataURL();
console.log(dataURL);
// Logs data:image/png;base64,wL2dvYWwgbW9yZ...
// Convert to Base64 string
const base64 = getBase64StringFromDataURL(dataURL);
console.log(base64);
// Logs wL2dvYWwgbW9yZ...
</script>
By default the canvas outputs to a lossless PNG, we can pass 'image/png', 'image/jpeg' or 'image/webp' to the toDataURL method to get a different format.
When using 'image/jpeg' or 'image/webp' we can pass the image compression as the last argument, 0 means a lot of compression, 1 means no compression.
<canvas width="300" height="150" id="my-canvas"></canvas>
<script>
const canvas = document.getElementById('my-canvas');
// Convert canvas to dataURL and log to console
const dataURL = canvas.toDataURL('image/jpeg', 0.5);
console.log(dataURL);
// Logs data:image/jpeg;base64,wL2dvYWwgbW9yZ...
// Convert to Base64 string
const base64 = getBase64StringFromDataURL(dataURL);
console.log(base64);
// Logs wL2dvYWwgbW9yZ...
</script>
If our image is an element we can fetch the image src and convert that to a Base64 string.
Alternatively we can draw the image to a canvas and then convert the canvas to an image element, this would be useful if we’re looking for a specific image format.
If the image is located on a remote server the CORS configuration of the remote server must allow our local script to access the image.
Note that the MIME type returned by remote server in the Content-Type response header is reflected in the DataURL.
If the MIME type is incorrect the DataURL will be incorrect as well.
<img src="my-image.jpeg" id="my-image" />
<script>
const image = document.getElementById('my-image');
// Get the remote image as a Blob with the fetch API
fetch(image.src)
.then((res) => res.blob())
.then((blob) => {
// Read the Blob as DataURL using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {
console.log(reader.result);
// Logs data:image/jpeg;base64,wL2dvYWwgbW9yZ...
// Convert to Base64 string
const base64 = getBase64StringFromDataURL(reader.result);
console.log(base64);
// Logs wL2dvYWwgbW9yZ...
};
reader.readAsDataURL(blob);
});
</script>
Drawing the image to a canvas first allows us to convert it to a different format.
Please note that this approach is slower than simply fetching the image src as shown in the previous example.
An additional caveat is that the canvas element has a maximum size, for some browsers this size limit is very low causing problems when converting the image.
<img src="my-image.jpeg" id="my-image" />
<script>
const image = document.getElementById('my-image');
const toDataURL = () => {
const canvas = document.createElement('canvas');
// We use naturalWidth and naturalHeight to get the real image size vs the size at which the image is shown on the page
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
// We get the 2d drawing context and draw the image in the top left
canvas.getContext('2d').drawImage(image, 0, 0);
// Convert canvas to DataURL and log to console
const dataURL = canvas.toDataURL();
console.log(dataURL);
// logs data:image/png;base64,wL2dvYWwgbW9yZ...
// Convert to Base64 string
const base64 = getBase64StringFromDataURL(dataURL);
console.log(base64);
// Logs wL2dvYWwgbW9yZ...
};
// If the image has already loaded, let's go!
if (image.complete) toDataURL(image);
// Wait for the image to load before converting
else image.onload = toDataURL;
</script>
Converting JavaScript file objects or blobs to Base64 strings can be useful. For example when we can only send string based data to the server. In this tutorial we’ll explore how to use JavaScript to generate a Base64 string and a DataURL from a file object.
We use FileReader to convert the file object to a dataUR this is done by using the readAsDataURL method.
<input type="file" />
<script>
// Get a reference to the file input
const fileInput = document.querySelector('input');
// Listen for the change event so we can capture the file
fileInput.addEventListener('change', (e) => {
// Get a reference to the file
const file = e.target.files[0];
// Encode the file using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {
console.log(reader.result);
// Logs data:<type>;base64,wL2dvYWwgbW9yZ...
};
reader.readAsDataURL(file);
});
</script>
The snippet below creates a base64 string, it’s identical to the previous example but it uses a regular expression to remove the Data URL part.
<input type="file" />
<script>
// Get a reference to the file input
const fileInput = document.querySelector('input');
// Listen for the change event so we can capture the file
fileInput.addEventListener('change', (e) => {
// Get a reference to the file
const file = e.target.files[0];
// Encode the file using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {
// Use a regex to remove data url part
const base64String = reader.result
.replace('data:', '')
.replace(/^.+,/, '');
console.log(base64String);
// Logs wL2dvYWwgbW9yZ...
};
reader.readAsDataURL(file);
});
</script>
Sometimes we just want to use an File object as an image source. But how to add the file object to the src attribute?
The URL.createObjectURL() method can help here.
The following code snippet will update the image source to the file that is loaded in the file input.
<input type="file" accept="image/*" />
<img src="" alt="" />
<script>
// Get a reference to the file input
const imageElement = document.querySelector('img');
// Get a reference to the file input
const fileInput = document.querySelector('input');
// Listen for the change event so we can capture the file
fileInput.addEventListener('change', (e) => {
// Get a reference to the file
const file = e.target.files[0];
// Set file as image source
imageElement.src = URL.createObjectURL(file);
});
</script>
We need to make sure to revoke the URL if we no longer need the file. If we don’t this causes memory leaks.
URL.revokeObjectURL(fileUrl);