user1131308
user1131308

Reputation: 309

Can javascript access the binary data in an image that's loaded via <img src=

if I have something like

<img src="x.jpg" id=i>

is there away to access the binary using something like getElementById("i").something ?

Upvotes: 1

Views: 2132

Answers (1)

vsync
vsync

Reputation: 130165

From an MDN demo:

They show in the below example how to fetch an image using an XHR request wrapped in a Promise. (you don't really need the promise part, but it's cool).

Just make sure the images are on the same domain which this code runs on, or wrap with JSONP.

And to your question, you could iterate on all the images on the page, and run the imgLoad function with their src, to get the data. I can't think of a way to access the data of an image that was already downloaded through the browser's own mechanism (src='...')

function imgLoad(url) {
    // Create new promise with the Promise() constructor;
    // This has as its argument a function
    // with two parameters, resolve and reject
    return new Promise(function(resolve, reject) {
      // Standard XHR to load an image
      var request = new XMLHttpRequest();
      request.open('GET', url);
      request.responseType = 'blob';

      // When the request loads, check whether it was successful
      request.onload = function() {
        if (request.status === 200) {
        // If successful, resolve the promise by passing back the request response
          resolve(request.response);
        } else {
        // If it fails, reject the promise with a error message
          reject(Error('Error code:' + request.statusText));
        }
      };

      request.onerror = function() {
      // Also deal with the case when the entire request fails to begin with
      // This is probably a network error, so reject the promise with a message
          reject(Error('There was a network error.'));
      };

      // Send the request
      request.send();
    });
}

// Get a reference to the body element, and create a new image object
var body = document.querySelector('body');
var myImage = new Image();

// Call the function with the URL we want to load, but then chain the
// promise then() method on to the end of it. This contains two callbacks
imgLoad('myLittleVader.jpg')
    .then(function(response) {
        // The first runs when the promise resolves, with the request.reponse
        // specified within the resolve() method.
        var imageURL = window.URL.createObjectURL(response);
        myImage.src = imageURL;
        body.appendChild(myImage);
        // The second runs when the promise
        // is rejected, and logs the Error specified with the reject() method.
    }, 
    function(Error) {
        console.log(Error);
    });

Upvotes: 1

Related Questions