有两种方法可以实现:
- 使用
XMLHttpRequest()
或fetch()
加载图像源,而不是使用图像元素
- 通过画布元素转换图像元素。这将重新压缩图像导致一定程度的质量损失。还存在“风险”,即图片包含ICC / gamma信息和/或浏览器支持此信息的情况下可能发生颜色/伽马变化。 即使只想表示原始图像为blob,请使用第1种方法,否则图像将与原始图像不完全相同。
对于第一个方法,并且由于您已经使用了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)}
});
}
然后可以像这样使用它获取图像的Blob:
loadXHR("url-to-image").then(function(blob) {
// here the image is a blob
});
或者在支持fetch的浏览器中使用fetch()
:
fetch("url-to-image")
.then(function(response) {
return response.blob()
})
.then(function(blob) {
});
另一种方法需要使用画布:
var img = new Image;
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
img.onload = function() {
c.width = this.naturalWidth;
c.height = this.naturalHeight;
ctx.drawImage(this, 0, 0);
c.toBlob(function(blob) {
}, "image/jpeg", 0.75);
};
img.crossOrigin = "";
img.src = "url-to-image";
var blob = new Blob([dataURI], {type : 'image/svg+xml'});
这段代码的作用是创建一个Blob对象,其中包含一个dataURI字符串,表示一个SVG图像。{type : 'image/svg+xml'}
设置了Blob对象的MIME类型为SVG图像类型。 - Muhammad Umer