使用javascript将图像转换为blob [英] convert image into blob using javascript

查看:202
本文介绍了使用javascript将图像转换为blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use promise to download an image and get the image data like:

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

我有图像,如:

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

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

how can I convert the image into a blob? (Similar to below snippet)

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

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

how can I get/access the [????] from the image ? I don't know how to get the image context.

推荐答案

你可以用两种方式做到这一点:

You can do this in two ways:


  • 使用 XMLHttpRequest() fetch()加载图像源而不是图像元素

  • 通过canvas元素转换图像元素。这将重新压缩图像,导致一些质量损失。根据图像包含ICC /伽玛信息和/或浏览器支持该信息,还存在颜色/伽马变化的风险。 IE浏览器。图像与原始图像不完全相同 - 如果您只想将原始图像表示为blob,请使用方法1.

  • Load the image source using XMLHttpRequest() or fetch() instead of an image element
  • Convert image element via a canvas element. This will recompress the image causing some quality loss. There is also the "risk" of color/gamma changes depending of the image contains ICC/gamma information and/or the browser support this information. Ie. the image won't be exact the same as the original - if you just want the original image to be represented as a blob, use method 1.

对于方法一,既然你已经在使用promises,你可以这样做:

For method one and since you're already using promises, you can do:

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获取图像:

Then get the image as Blob using it like this:

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";

这篇关于使用javascript将图像转换为blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆