Home >Web Front-end >JS Tutorial >How Can I Get Base64-Encoded Image Data from Already Loaded Images in JavaScript?

How Can I Get Base64-Encoded Image Data from Already Loaded Images in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 22:56:11625browse

How Can I Get Base64-Encoded Image Data from Already Loaded Images in JavaScript?

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:

  1. Create a Canvas: Generate a canvas element with dimensions matching the image's size.
  2. Copy Image Data: Utilize the drawImage function to transfer the image's data to the canvas.
  3. Obtain Data URL: Employ the toDataURL function to retrieve the base64-encoded image data from the canvas.
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!

Statement:
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