簡體   English   中英

使用javascript將圖像轉換為blob

[英]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()而不是圖像元素加載圖像源
  • 通過畫布元素轉換圖像元素。 這將重新壓縮圖像,導致一些質量損失。 根據圖像包含 ICC/gamma 信息和/或瀏覽器支持此信息,還存在顏色/gamma 變化的“風險”。 IE。 圖像不會與原始圖像完全相同 - 如果您只想將原始圖像表示為 blob,請使用方法 1。

對於方法一,由於您已經在使用 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";

你可以試試這個節點模塊

https://www.npmjs.com/package/image-to-blob

或者您可以將圖像轉換為畫布,然后轉換為 blob uri:

https://github.com/blueimp/JavaScript-Canvas-to-Blob

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM