美文网首页
H5调用手机相机和相册,并且将图片转化为base64的格式

H5调用手机相机和相册,并且将图片转化为base64的格式

作者: 郝艳峰Vip | 来源:发表于2018-12-03 15:35 被阅读0次

    前沿:


    之前在做见到的时候有一个需求是更换头像,于是乎就开始各种趟坑,还好搞出来了,之前忙着上线,没时间整理,现在抽空整理一下。本补充一下,这个项目是很早的项目,用的还是jq
    ,h5,写的还不是vue全家桶。

    step一,首先需要用一个button来代替一个隐藏的input file,

    accept="image/*"代表唤起相册
    capture="camera" 代表唤起相机

    <input type="file" onchange="duqu_wenjian(this)" accept="image/*" capture="camera" id="shouji_xingce" style="display: none; " />
    <div class="header_on_center_touxiang"></div>
    

    step二,接下来看看js怎么写

    点击代替的按钮时出发`<input type="file">`的点击事件
    $(".header_on_center_touxiang ").on("click ", function() {
                            $("#shouji_xingce").click();
                      });
    
    
    function duqu_wenjian(source) {
                            var file= source.files[0]
                           if(window.FileReader)  {
                                  var fr = new FileReader();
                                     fr.onloadend = function(e) {
                                        var image = e.target.result; ///这是转换后的图片
                                    fr.readAsDataURL(file);
                                   }
           }
    }
    
    

    结束:
    这样就完成了一个上传图片的并转换为base64的功能。之前的项目,没有封装,直接用就好了。

    相关文章

      网友评论

          本文标题:H5调用手机相机和相册,并且将图片转化为base64的格式

          本文链接:https://www.haomeiwen.com/subject/ycvycqtx.html