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 =this;
return new Promise((resolve,reject)=>{//异步处理
let canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d"),
image = new Image(),
fontSize,//水印的大小
MAX_WH = 800;//图片的最大宽高比,因为在以上方法中获取的照片size太大,上传时耗时太多所以需要做处理
image.crossOrigin = "Anonymous";
image.onload = function() {//这里是一个异步,所以获取到的base64文件需要用回调
if (image.height>MAX_WH) {
image.width *= MAX_WH/image.height;
image.height = MAX_WH
}
if (image.width>MAX_WH) {
image.height *= MAX_WH/ image.width;
image.width = MAX_WH;
}
canvas.height = image.height;
canvas.width = image.width;
ctx.drawImage(image, 0, 0,image.width,image.height);
if(image.width>100 && image.width<500){
fontSize = '24px'
}else if(image.width>=500 && image.width<1000){
fontSize = '44px'
}else if(image.width>=1000 && image.width<1500){
fontSize = '64px'
}
ctx.font =`${fontSize} Arial`;
ctx.fillStyle = "tomato";
let time = that.getCurrnetTime("timeSign");//获取当前的时间
ctx.textAlign = "end";
ctx.textBaseline = "middle";
ctx.fillText(time,image.width-20,image.height-60);
let dataURL = canvas.toDataURL( "image/png/jpg");
if(dataURL) {
resolve(dataURL)
}else{
reject("err")
}
};
image.src = url
})
},
//调用此方法之后文件就转为base64格式了
如需要file文件格式,见https://blog.csdn.net/weixin_42307283/article/details/103613682