Home > Web Front-end > JS Tutorial > How Can I Get an Image's Base64 Data URL Using JavaScript?

How Can I Get an Image's Base64 Data URL Using JavaScript?

DDD
Release: 2024-12-15 22:12:16
Original
518 people have browsed it

How Can I Get an Image's Base64 Data URL Using JavaScript?

How to Retrieve Image Data URL Using JavaScript

In web development, it is often useful to access the content of images on a web page. This can be achieved through JavaScript, allowing developers to manipulate and utilize image data without having to download it separately.

One such use case involves obtaining the base64-encoded representation of images that have already been loaded by the browser. This is particularly beneficial when working with Greasemonkey scripts in Mozilla Firefox.

To get the image data URL, a canvas element is used. Here's the code you can use:

function getBase64Image(img) {
  // Create a canvas with dimensions matching the image
  const canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;

  // Copy the image data onto the canvas
  const ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);

  // Get the base64-encoded image
  const dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
Copy after login

However, it's important to note that this method only works for images from the same domain as the page. Alternatively, you can specify the crossOrigin="anonymous" attribute on the image tag and ensure the server supports CORS.

Remember, this method provides a re-encoded version of the image, not the original file. For an identical result, consider using other methods such as Kaiido's answer.

The above is the detailed content of How Can I Get an Image's Base64 Data URL Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template