code to convert image to binary data in javascript

You can use the FileReader API to read the contents of an image file as binary data. Here's an example code to convert an image to binary data:

index.tsx
function convertImageToBinaryData(imageURL) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', imageURL, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = () => {
      if (xhr.status === 200) {
        const arrayBuffer = xhr.response;
        const binaryString = String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
        const base64String = btoa(binaryString);
        resolve(base64String);
      } else {
        reject(new Error('Failed to load image'));
      }
    };
    xhr.send();
  });
}

// Usage
convertImageToBinaryData('/path/to/image.jpg')
  .then((binaryData) => {
    console.log(binaryData);
  })
  .catch((error) => {
    console.error(error);
  });
749 chars
28 lines

In the example above, we use XMLHttpRequest to download the image file as an array buffer. Then, we convert the array buffer to a binary string and use the btoa function to convert the binary string to base64-encoded binary data, which can be used to embed the image data in HTML or send it to the server.

related categories

gistlibby LogSnag