Extracting Image Data URLs in JavaScript
Problem:
How can you obtain base64-encoded content from images already loaded in a browser using HTML tags, without the need for re-downloading?
Solution for Greasemonkey and Firefox:
To extract the content of fully loaded images using Greasemonkey and Firefox, implement the following steps:
function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); var dataURL = canvas.toDataURL("image/png"); return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); }
Note: This solution assumes image data is available from the same domain as the page or has the crossOrigin="anonymous" attribute enabled with server support for CORS. Additionally, the returned image may be re-encoded.
The above is the detailed content of How Can I Get Base64-Encoded Image Data from Already Loaded Images in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!