[英]convert image into blob using javascript
我使用 promise 下載圖像並獲取圖像數據,例如:
promise.downloadFile().then(function(image){
//do something
});
我得到了圖像,就像:
<img name="imageXXX" crossorigin="" src="/images/grass.jpg">
如何將圖像轉換為 blob? (類似於下面的片段)
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";
你可以試試這個節點模塊
或者您可以將圖像轉換為畫布,然后轉換為 blob uri:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.