我使用promise来下载图像并获取图像数据,如:
promise.downloadFile().then(function(image){
//do something
});
我有图像,就像:
<img name="imageXXX" crossorigin="" src="/images/grass.jpg">
如何将图像转换为blob? (类似于下面的代码片段)
var blob = new Blob([????], "image/jpg");
如何从图像中获取/访问[????]?我不知道如何获取图像上下文。
答案 0 :(得分:27)
您可以通过两种方式执行此操作:
XMLHttpRequest()
或fetch()
而非图片元素对于方法一,既然你已经使用了promises,你可以这样做:
function loadXHR(url) {
return new Promise(function(resolve, reject) {
try {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.onerror = function() {reject("Network error.")};
xhr.onload = function() {
if (xhr.status === 200) {resolve(xhr.response)}
else {reject("Loading error:" + xhr.statusText)}
};
xhr.send();
}
catch(err) {reject(err.message)}
});
}
然后像这样使用它获取图像:
loadXHR("url-to-image").then(function(blob) {
// here the image is a blob
});
或在fetch()
中使用browsers which support:
fetch("url-to-image")
.then(function(response) {
return response.blob()
})
.then(function(blob) {
// here the image is a blob
});
另一种方法需要画布:
var img = new Image;
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
img.onload = function() {
c.width = this.naturalWidth; // update canvas size to match image
c.height = this.naturalHeight;
ctx.drawImage(this, 0, 0); // draw in image
c.toBlob(function(blob) { // get content as JPEG blob
// here the image is a blob
}, "image/jpeg", 0.75);
};
img.crossOrigin = ""; // if from different origin
img.src = "url-to-image";
答案 1 :(得分:0)
您可以尝试此节点模块
或者您可以将图像转换为画布,然后转换为blob uri: