前端
$(".jxs_sq_div_list img").on('click',function () { takePicture(this) }); function takePicture(e) { wx.chooseImage({ count: 1, needResult: 1, sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (data) { localIds = data.localIds[0]; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 wx.getLocalImgData({ localId: localIds, // 图片的localID success: function (res) { var localData = res.localData; // localData是图片的base64数据,可以用img标签显示 $.ajax({ type: "post", url: "{:U('Index/saveBase64Image')}", data: { "base64_image_content":localData }, cache: false, async : true, dataType: "json", success: function (rey) { $(e).attr('src',rey); }, error:function (XMLHttpRequest, textStatus, errorThrown) { layer.msg('请求失败!'); } }); },fail:function(res){ alert("显示失败"); } }); }, fail: function (res) { ik_mobel_gb(); alterShowMessage("操作提示", JSON.stringify(res), "1", "确定", "", "", ""); } }); }
PHP
//base64图片上传 public function saveBase64Image(){ $base64_image_content = $_POST['base64_image_content']; $fenge = explode(":",$base64_image_content); if(count($fenge) < 2){ $base64_image_content = "data:image/png;base64,".$base64_image_content; } //设置图片保存路径 $path = "Public/Uploads/".date("Y-m-d",time())."/"; if (!is_dir($path)){ //判断目录是否存在 不存在就创建 mkdir($path,0777,true); } $imageName = "25220_".date("His",time())."_".rand(1111,9999).'.png'; $data = $this->base64_image_content($base64_image_content,$path,$imageName); $data = C('url').$data; $this->ajaxReturn($data); }
注意:如果为微信公众号的话需要先获取相机权限,否则无法调用相机接口!