Ask Your Question
2

How can I obtain the data string/buffer of an image in JavaScript without making an extra network request?

asked 2023-03-07 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-06-06 21:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-07 11:00:00 +0000

Seen: 8 times

Last updated: Jun 06 '21