javascript 在javascript中转换base64字符串中的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13034212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:40:54  来源:igfitidea点击:

Converting the image in base64 string in javascript?

javascripthtmlbase64

提问by M Sach

i have html form with ENCTYPE="multipart/form-data" .It just contains the textbox of type 'file' which browses the file from local box.Here is the textbox code snippet

我有一个带有 ENCTYPE="multipart/form-data" 的 html 表单。它只包含从本地框中浏览文件的“文件”类型的文本框。这是文本框代码片段

<td>
    <input name="fileNameAttr" id="filePath" size="52" type="file" value="">
</td>

I browse the file some image file from local box. The moment i select the file, filePath gets populated in text box. Now on click of some button, i want to convert the image in to base64 String in javascript. I am not using HTML5. Can i achieve it in javascript?

我从本地框中浏览了一些图像文件。我选择文件的那一刻,filePath 将填充在文本框中。现在单击某个按钮,我想将图像转换为 javascript 中的 base64 字符串。我没有使用 HTML5。我可以在 javascript 中实现它吗?

i can see some solution on net using HTML5 but that does not solve my purpose. If i need to use some third party utility , i can do that.

我可以在网上看到一些使用 HTML5 的解决方案,但这并不能解决我的目的。如果我需要使用某些第三方实用程序,我可以这样做。

EDIT:-looks like jquery can help with $.base64.encode( "this is a test" ); but how to use it with type="file"?

编辑:-看起来 jquery 可以帮助 $.base64.encode( "this is a test" ); 但是如何将它与 type="file" 一起使用?

回答by NullPoiиteя

this can be done by the HTML5 <canvas>for it

这可以通过HTML5来实现<canvas>

or

或者

if you have node.js as an option then try something like that in img

如果你有 node.js 作为选项,那么在 img 中尝试类似的东西

or <img src="data:image/png;base64,jkasfhsdjkhsadf" />

或者 <img src="data:image/png;base64,jkasfhsdjkhsadf" />

example

例子

var fs = require('fs');
var base64_data = new Buffer(fs.readFileSync('sample.png')).toString('base64');
console.log('<img alt="sample" src="data:image/png;base64,' + base64_data + '">');

check this (also source of example)

检查这个(也是例子的来源)

Data URI scheme

数据URI方案

Good read

好读

  1. How can you encode to Base64 using Javascript?//its for image
  1. 如何使用 Javascript 编码为 Base64?//它的图像

回答by Gung Foo

If you could access the local filesystem via javascript, what would keep you from reading the password file or other private data?

如果您可以通过 javascript 访问本地文件系统,什么会阻止您读取密码文件或其他私人数据?

This you can't do and it can't and won't be allowed in the future, for obvious reasons!

出于显而易见的原因,您不能这样做,将来也不能也不允许这样做!