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,/, ""); }
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!