JavaScript如何从XMLHttpRequest获取图像宽度和高度

时间:2016-02-01 18:13:50

标签: javascript

我正在将从Canvas转换为base 64的映像的跨站点请求的实现切换到XMLHttpRequest和FileReader,以便可以在Web worker中使用它。而且我想知道是否有办法从一开始就获得图像的宽度和高度。

新功能

var convertFileToDataURLviaFileReader = function (url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function () {
        var reader = new FileReader();
        reader.onloadend = function () {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };

    // Our workaround for the Amazon CORS issue
    // Replace HTTPs URL with HTTP
    xhr.open('GET', url.replace(/^https:\/\//i, 'http://'));
    xhr.send();
}

我们的旧功能

var convertImgToDataURLviaCanvas = function(url, callback, outputFormat) {
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);

        var allInfo = {
            data: dataURL,
            width: this.width,
            height: this.height
        }

        // Add height and width to callback
        callback(allInfo);
        canvas = null;
    };

    // Our workaround for the Amazon CORS issue
    // Replace HTTPs URL with HTTP
    img.src = url.replace(/^https:\/\//i, 'http://');
}

在旧函数中,我可以用画布获得高度和宽度,我在var allInfo内部这样做。是否存在FileReader的等价物或某种方式来获取新函数的宽度和高度?

为了澄清,我正在切换到XMLHttpRequest,因为Web Workers无法访问DOM,因此无法使用Canvas。

1 个答案:

答案 0 :(得分:1)

看一下这段代码,它只是对这个例子的快速修改https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

你的reader.result是base 64编码的字符串吗?

  <form>
    <input type="file" onchange="previewFile()"><br>
    <img src="" alt="Image preview..."><!-- height and width are not set -->
  </form>
  <script>
    var previewFile = () => {

      "use strict";

      let file = document.querySelector("input[type=file]").files[0];
      let fileReader = new FileReader();
      let preview = document.querySelector("img")

      fileReader.addEventListener("load", () => {
        preview.src = fileReader.result;
        // here preview.height and preview.width are accessible
        // if height and width are not set in the img element in the html
      });

      if (file) {
        fileReader.readAsDataURL(file);
      }
    };
  </script>