【问题标题】:convert image into blob using javascript使用javascript将图像转换为blob
【发布时间】:2017-07-17 05:45:58
【问题描述】:

我使用 Promise 下载图像并获取图像数据,例如:

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

我得到了图像,它是这样的:

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

如何将图像转换为 blob? (类似于下面的sn-p)

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

如何从图像中获取/访问 [??????] ?我不知道如何获取图像上下文。

【问题讨论】:

  • “我使用 promise 来下载图像”那么如果你正在下载,你可能应该得到一个 base64 版本而不是 URL,对吧?
  • var blob = new Blob([dataURI], {type : 'image/svg+xml'});

标签: javascript image blob


【解决方案1】:

你可以试试这个节点模块

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

或者您可以将图像转换为画布,然后转换为 blob uri:

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

【讨论】:

    【解决方案2】:

    您可以通过两种方式做到这一点:

    • 使用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
    });
    

    或在browsers which support 中使用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 this 处理程序内的上下文(使用 function() 时)是图像本身。这允许您在多个图像实例之间共享然后处理程序,并始终确保您正在处理正确的图像。有关详细信息,请参阅devdocs.io/javascript/operators/this
    • 我想知道在 canvas 方法中,img.crossOrigin = "" 的变量应该是什么?
    • 拯救了这一天!赞!!
    猜你喜欢
    • 2017-11-13
    • 2020-06-16
    • 2016-05-29
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2013-07-08
    • 2022-01-20
    相关资源
    最近更新 更多