H5移动端打开摄像头和打开相册
参考文档:http://www.html5plus.org/doc/zh_cn/camera.html
!!!plus在PC端运行时会报错,只有打包后在手机端运行时才能运行
//选择打开摄像头还是打开相册takePhoto(){let that = this;let bts = [{title: "拍照"},{title: "从相册选择"}];plus.nativeUI.actionSheet({cancel: "取消",buttons: bts},function(e) {if (e.index == 1) {that.getCamera();} else if (e.index == 2) {that.getImg();}});},
//打开摄像头
getCamera(){let that = this;let cmr = plus.camera.getCamera();//这里配置其实不起作用let res = cmr.supportedImageResolutions[14];let fmt = cmr.supportedImageFormats[0];cmr.captureImage(function(path){//获取拍照后的真实地址plus.io.resolveLocalFileSystemURL(path,function(entry) {//通过URL参数获取目录对象或文件对象console.log("拍照获取的真实路径",entry.fullPath)that.takeImgs.push(entry.fullPath);//直接可以显示的类型var imgSrc = entry.toLocalURL();//获取目录路径转换为本地路径URL地址console.log("imgSrcimgSrc",imgSrc)that.takeImgSrc.push(imgSrc);//URL地址型方便于转换base64},function(e) {console.log(e.message);},{ resolution: res, format: fmt });})},//打开相册getImg(){let that = this;plus.gallery.pick(function(path) {that.takeImgs.push(path);that.takeImgSrc.push(path);},function(e) {console.log("取消选择图片");},{ filter: "image" });},
以上就是如何在移动端打开摄像头和相册获取照片的方式。但是在实际项目可能后端想要的图片格式是不确定的,可能是base64.可能是file文件对象,所以我们要对获取到的照片处理成相对应的格式
/* 照片转码成base64加上时间水印 */getBase64Time(url){let that &#61;this;return new Promise((resolve,reject)&#61;>{//异步处理let canvas &#61; document.createElement("canvas"),ctx &#61; canvas.getContext("2d"),image &#61; new Image(),fontSize,//水印的大小MAX_WH &#61; 800;//图片的最大宽高比&#xff0c;因为在以上方法中获取的照片size太大&#xff0c;上传时耗时太多所以需要做处理image.crossOrigin &#61; "Anonymous";image.onload &#61; function() {//这里是一个异步&#xff0c;所以获取到的base64文件需要用回调if (image.height>MAX_WH) {image.width *&#61; MAX_WH/image.height;image.height &#61; MAX_WH}if (image.width>MAX_WH) {image.height *&#61; MAX_WH/ image.width;image.width &#61; MAX_WH;}canvas.height &#61; image.height;canvas.width &#61; image.width;ctx.drawImage(image, 0, 0,image.width,image.height);if(image.width>100 && image.width<500){fontSize &#61; &#39;24px&#39;}else if(image.width>&#61;500 && image.width<1000){fontSize &#61; &#39;44px&#39; }else if(image.width>&#61;1000 && image.width<1500){fontSize &#61; &#39;64px&#39;}ctx.font &#61;&#96;${fontSize} Arial&#96;;ctx.fillStyle &#61; "tomato"; let time &#61; that.getCurrnetTime("timeSign");//获取当前的时间ctx.textAlign &#61; "end";ctx.textBaseline &#61; "middle";ctx.fillText(time,image.width-20,image.height-60);let dataURL &#61; canvas.toDataURL( "image/png/jpg"); if(dataURL) {resolve(dataURL)}else{reject("err")}};image.src &#61; url})},//调用此方法之后文件就转为base64格式了
如需要file文件格式&#xff0c;见https://blog.csdn.net/weixin_42307283/article/details/103613682