javascript可以访问通过<img src=加载的图像中的二进制数据吗?

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

本文关键字:图像 加载 二进制 数据 src img 访问 javascript      更新时间:2023-09-26

如果我有像

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

可以使用类似getElementById("i")的方法访问二进制文件。什么?

来自MDN演示:

它们在下面的例子中展示了如何使用包装在Promise中的XHR请求来获取图像。(你真的不需要承诺的部分,但这很酷)。

请确保图像在此代码运行的同一域上,或者使用JSONP包装。

对于您的问题,您可以迭代页面上的所有图像,并运行imgLoad函数和它们的src,以获得数据。我想不出一种方法来访问已经通过浏览器自己的机制下载的图像的数据(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);
    });