You can convert an image to a base64-encoded string using the HTMLCanvasElement toDataURL() method. Here is an example code:
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL();
const data = atob(dataURL.split(',')[1]);
const bytes = new Uint8Array(data.length);
for (let i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
console.log('Image data buffer:', bytes.buffer);
};
img.src = 'image.jpg';
In this example code, we first load an image and when it is loaded, we create a canvas element, draw the image onto it, and then convert the canvas to a data URL. The data URL is a base64-encoded string, which we can convert back to binary data using the atob() function. We then create a new Uint8Array from the binary data and access its underlying ArrayBuffer using the buffer property. This is the buffer containing the image data.
Asked: 2023-03-07 11:00:00 +0000
Seen: 8 times
Last updated: Jun 06 '21