项目作者: b5156

项目描述 :
image file to base64
高级语言: JavaScript
项目地址: git://github.com/b5156/imgfile2base64.git
创建时间: 2017-08-18T07:35:34Z
项目社区:https://github.com/b5156/imgfile2base64

开源协议:

下载


imgfile2base64

imgfile2base64能将一个image文件转换成base64字符串,基于canvasFileReader,在浏览器中使用。

用法:

npm i imgfile2base64

<script src="imgfile2base64.js"></script>

  1. imgfile2base64(file, function (base64) {
  2. console.log(base64); // data:image/jpeg;base64,.....
  3. });

参数:

  • file:File,一个File对象。通常从 <input type=“file” /> 获取。
  • complete:Function,一个回调函数,将在转换完成后执行,它的参数便是base64字符串。
  • opt:Object,一个object对象,一些参数。
    • quality:Number,一个介于0~1之间的值,用来设定图片质量,默认值:1。
    • widht:Number,用来设定图片宽度,默认值:原图的宽度。
    • height:Number,用来设定图片高度,默认值:原图高度。

例子:

查看效果

  1. <input id="file" type="file"/>
  2. <img id="img" src=""/>
  1. document.getElementById('file').addEventListener('change',
  2. function (e) {
  3. var file = e.target.files[0];
  4. imgfile2base64(file, function (base64) {
  5. document.getElementById('img').setAttribute('src', base64);
  6. }, {
  7. width: 100,
  8. quality: 0.5
  9. });
  10. }
  11. )

License

MIT licensed.