mui调用本地相册和拍照功能
图例
只用更改上传图片ajax部分代码即可
1、html
<div class="headdiv"> <img src="" id="userImg"/> </div>
2、js
<script> /*调相机本地相抵上传图片*/ mui.plusReady(function(){ document.getElementById('userImg').addEventListener('tap',function(){ if(mui.os.plus){ var a=[{ title:'拍照' },{ title:'从手机相册选择' }]; plus.nativeUI.actionSheet({ // title:'修改头像', cancel:'取消', buttons:a },function(b){ switch(b.index){ case 0: break; case 1: //拍照 getImages(); break; case 2: //打开相册 galleryImages(); break; default: break; } },false); } }); //拍照 function getImages(){ var mobileCamera=plus.camera.getCamera(); mobileCamera.captureImage(function(e){ plus.io.resolveLocalFileSystemURL(e,function(entry){ var path=entry.toLocalURL()+'?version='+new Date().getTime(); uploadHeadImg(path); console.log(path); },function(err){ console.log("读取拍照文件错误"); }); },function(e){ console.log("er",err); },function(){ filename:'_doc/head.png'; }); } //本地相册选择 function galleryImages() { plus.gallery.pick(function(a) { plus.io.resolveLocalFileSystemURL(a, function(entry) { plus.io.resolveLocalFileSystemURL("_doc/", function(root) { root.getFile("head.png", {}, function(file) { //文件已存在 file.remove(function() { console.log("file remove success"); entry.copyTo(root, 'head.png', function(e) { var e = e.fullPath + "?version=" + new Date().getTime(); $("#userImg").attr("src",e); console.log(e); uploadHeadImg(e); /*上传图片*/ //变更大图预览的src //目前仅有一张图片,暂时如此处理,后续需要通过标准组件实现 }, function(e) { console.log('copy image fail:' + e.message); }); }, function() { console.log("delete image fail:" + e.message); }); }, function() { //文件不存在 entry.copyTo(root, 'head.png', function(e) { var path = e.fullPath + "?version=" + new Date().getTime(); uploadHeadImg(path); /*上传图片*/ }, function(e) { console.log('copy image fail:' + e.message); }); }); }, function(e) { console.log("get _www folder fail"); }) }, function(e) { console.log("读取拍照文件错误:" + e.message); }); }, function(a) {}, { filter: "image" }) }; function uploadPics(u) { var urls = u.src; var img = new Image(); img.src = urls; img.onload = function() { var that = img; var w = that.width, h = that.height, scale = w / h; w = 320 || w; h = w / scale; var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); $(canvas).attr({ w, height: h }); ctx.drawImage(that, 0, 0, w, h); var base64 = canvas.toDataURL("image/jpeg", 1); //1 || 0.8 var aa = { "fileData": base64 }; $.ajax({ async: false, //是否异步 cache: false, //是否使用缓存 type: "POST", data: JSON.stringify(aa), dataType: "json", contentType: "application/json", url: "http://", //改变此处的接口名即可 success: function(results) { u.src = "http://" + results.result; }, error: function(result) { alert("系统繁忙!"); } }); } } //上传图片 function uploadHeadImg(imgPath){ //选中图片之后,头像当前的照片变为选择的照片 var mainImg=document.getElementById('userImg'); uploadPics(mainImg); } }); </script>