使用JavaScript将图像转换为Blob

46

我使用 Promise 下载图片并获取图片数据,代码如下:

promise.downloadFile().then(function(image){                
    //do something
});

我已经得到了这张图片,它长这样:

<img name="imageXXX" crossorigin="" src="/images/grass.jpg">

我该如何将图像转换为Blob?(类似下面的代码片段)

var blob = new Blob([????], "image/jpg");

我该如何从这张图片中获取/访问 [????]?我不知道如何获取图片的上下文。


我使用 Promise 来下载图片,如果你正在下载,那么最好获取 Base64 版本而不是 URL,对吧? - mehulmpt
5
var blob = new Blob([dataURI], {type : 'image/svg+xml'});这段代码的作用是创建一个Blob对象,其中包含一个dataURI字符串,表示一个SVG图像。{type : 'image/svg+xml'}设置了Blob对象的MIME类型为SVG图像类型。 - Muhammad Umer
1个回答

75

有两种方法可以实现:

  • 使用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) {
    // 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";

@Martian2049 当使用function()时,处理程序内的this上下文是图像本身。这使您可以在多个图像实例之间共享处理程序,并始终确保您正在处理正确的图像。有关更多信息,请参见https://devdocs.io/javascript/operators/this。 - user1693593
我想知道在canvas方法中,img.crossOrigin = ""变量应该填什么? - netskink
这个 blob 每次都返回相同的图像。我该如何纠正这个问题? - Alia Anis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接