javascript可以访问通过<img src=加载的图像中的二进制数据吗?
Can javascript access the binary data in an image that's loaded via <img src=
如果我有像
<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);
});
相关文章:
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- 在检索数据时是否可以停止图像加载请求
- 如何让我的网站上的WEBP图像加载在morzilla firefox中有一个可能的解决方案吗?如果是,那么如何
- jQuery:获取图像加载错误的详细信息
- 在safari和chrome中,js图像加载产生了奇怪的结果
- 图像加载不适用于 IE 8 或更低版本
- 这个图像加载功能有什么作用
- JavaScript 图像加载器不起作用
- 动态图像加载是否会减少服务器过载
- 跨来源图像加载被拒绝-仅限iPhone-简单图像上传
- 纯javascript的进度图像加载程序仅当用户单击提交html表单时
- 使用JavaScript延迟图像加载
- 如果当前图像加载缓慢,如何加载其他图像
- HTML图像加载触发一个错误
- 将图像加载到localStorage,并将图像src设置到该位置
- jquery图像加载检查错误
- 将图像加载到织物画布背景中
- 需要在bootstrap css中单击时将图像加载为模态
- 正在显示加载..在将新图像加载到网站时播放动画
- 砖石事件:在图像加载和布局完成后调用事件