我使用 Promise 下载图像并获取图像数据,例如:
promise.downloadFile().then(function(image){
//do something
});
我已经得到了图像,如下所示:
<img name="imageXXX" crossorigin="" src="/images/grass.jpg">
如何将图像转换为斑点? (类似于下面的片段)
var blob = new Blob([????], "image/jpg");
如何从图像中获取/访问 [????] ?我不知道如何获取图像上下文。
您可以通过两种方式做到这一点:
XMLHttpRequest()
或 fetch()
而不是图像元素加载图像源对于方法一,由于您已经在使用 Promise,您可以这样做:
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)}
});
}
然后像这样使用 Blob 来获取图像:
loadXHR("url-to-image").then(function(blob) {
// here the image is a blob
});
或在支持的浏览器中使用
fetch()
:
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";
convertBase64ToBlob(base64String: string): Blob {
const parts = base64String.split(',');
const contentType = parts[0].split(':')[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength;
++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
用途:
convertBase64ToBlob("data:image/jpeg;base64," + image.base64String)
图像看起来像:
{
"format": "jpeg",
"base64String": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAQwAABtbnRyUkdC72Y+lWiVyXTnsyZdikwh+3qCevUcx4v17L9ZQTWqN3JUJEgrQy+h94fn+kCCCuLmv9E+XFgXwC/0Whqa3/9k=",
"exif": {
"DateTime": "2024:07:30 17:07:53",
"ImageLength": "208",
"ImageWidth": "208",
"LightSource": "0",
"Orientation": "0"
}
}
图像响应取自: