如何使用javascript将图像转换为字符串?

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

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

提前致谢。


慕斯709654
浏览 1186回答 2
2回答

POPMUISE

有<input&nbsp;type="file"&nbsp;id="picture">你可以为它添加一个事件处理程序来监听change事件(这段代码必须在上面的HTML之后或在DOMContentLoaded事件上注册)var&nbsp;input&nbsp;=&nbsp;document.getElementById('picture');input.addEventListener('change',&nbsp;handleFiles,&nbsp;false);然后你的handleFiles事件会将图像绘制到画布中并从文件中提取base64字符串:function&nbsp;handleFiles(e)&nbsp;{ &nbsp;&nbsp;var&nbsp;canvas&nbsp;=&nbsp;document.createElement('canvas'); &nbsp;&nbsp;var&nbsp;ctx&nbsp;=&nbsp;canvas.getContext('2d'); &nbsp;&nbsp;var&nbsp;img&nbsp;=&nbsp;new&nbsp;Image(); &nbsp;&nbsp;img.onload&nbsp;=&nbsp;function()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;ctx.drawImage(img,&nbsp;0,&nbsp;0); &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;base64&nbsp;=&nbsp;canvas.toDataURL(); &nbsp;&nbsp;&nbsp;&nbsp;console.log(base64); &nbsp;&nbsp;} &nbsp;&nbsp;img.src&nbsp;=&nbsp;URL.createObjectURL(e.target.files[0]);}运行示例如下:var input = document.getElementById('picture');input.addEventListener('change', handleFiles, false);function handleFiles(e) {&nbsp; var canvas = document.createElement('canvas');&nbsp; var ctx = canvas.getContext('2d');&nbsp; var img = new Image();&nbsp; img.onload = function() {&nbsp; &nbsp; ctx.drawImage(img, 0, 0);&nbsp; &nbsp; var base64 = canvas.toDataURL();&nbsp; &nbsp; document.getElementById('result').value = base64;&nbsp; }&nbsp; img.src = URL.createObjectURL(e.target.files[0]);}textarea {&nbsp; width: 350px;&nbsp; height: 100px;}<input type="file" id="picture" /><br /> <br /><textarea id="result"></textarea>

慕的地8271018

如果您想要的是dataURI版本,请使用a FileReader及其readAsDataURL()方法。file_input.onchange = function(e) {&nbsp; var fr = new FileReader();&nbsp; fr.onload = function() {&nbsp; &nbsp; output.src = this.result;&nbsp; }&nbsp; fr.readAsDataURL(this.files[0]);};<input type="file" id="file_input" /><img id="output" />如果您只想显示它,那么您可以使用URL构造函数:file_input.onchange = function(e) {&nbsp; output.src = URL.createObjectURL(this.files[0]);};// don't forget to revoke the URLObject when you don't need it anymoreoutput.onload = function() {&nbsp; URL.revokeObjectURL(this.src);}<input type="file" id="file_input" /><img id="output" />
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript