【问题标题】:How to convert an image to a string using javascript? [closed]如何使用javascript将图像转换为字符串? [关闭]
【发布时间】:2016-07-26 01:54:35
【问题描述】:
<input type="file" id="picture">

我想将上传到 html 输入的图像转换为字符串。如何使用 JavaScript 做到这一点?

提前致谢。

【问题讨论】:

标签: javascript html image


【解决方案1】:

如果您想要的是 dataURI 版本,请使用 FileReader 及其 readAsDataURL() 方法。

file_input.onchange = function(e) {

  var fr = new FileReader();
  fr.onload = function() {
    output.src = this.result;
  }
  fr.readAsDataURL(this.files[0]);

};
<input type="file" id="file_input" />
<img id="output" />

如果你只想显示它,那么你可以使用URL构造函数:

file_input.onchange = function(e) {

  output.src = URL.createObjectURL(this.files[0]);

};

// don't forget to revoke the URLObject when you don't need it anymore
output.onload = function() {
  URL.revokeObjectURL(this.src);
}
<input type="file" id="file_input" />
<img id="output" />

【讨论】:

    【解决方案2】:

    拥有

    <input type="file" id="picture">
    

    您可以为其添加一个事件处理程序以侦听更改事件(此代码必须位于上述 HTML 之后或在 DOMContentLoaded 事件上注册)

    var input = document.getElementById('picture');
    input.addEventListener('change', handleFiles, false);
    

    然后您的 handleFiles 事件会将图像绘制到画布中并从文件中提取 base64 字符串:

    function handleFiles(e) {
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
    
      var img = new Image();
    
      img.onload = function() {
        ctx.drawImage(img, 0, 0);
    
        var base64 = canvas.toDataURL();
        console.log(base64);
      }
    
      img.src = URL.createObjectURL(e.target.files[0]);
    }
    

    运行示例如下:

    var input = document.getElementById('picture');
    input.addEventListener('change', handleFiles, false);
    
    function handleFiles(e) {
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
    
      var img = new Image();
    
      img.onload = function() {
        ctx.drawImage(img, 0, 0);
    
        var base64 = canvas.toDataURL();
        document.getElementById('result').value = base64;
      }
    
      img.src = URL.createObjectURL(e.target.files[0]);
    }
    textarea {
      width: 350px;
      height: 100px;
    }
    <input type="file" id="picture" />
    <br /> <br />
    <textarea id="result"></textarea>

    【讨论】:

    • 然后你得到一个 300*150 的图像,无论你通过什么图像尺寸。此外,您已将图像转换为未优化的 png 版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2011-09-03
    • 1970-01-01
    • 2012-03-14
    相关资源
    最近更新 更多