// 选择拍照或者手机相册
take () {
let vm = this
if (mui.os.plus) {
var buttonTit = [{
title: "拍照"
}, {
title: "从手机相册选择"
}];
plus.nativeUI.actionSheet({
title: "上传图片",
cancel: "取消",
buttons: buttonTit
}, function(b) { /*actionSheet 按钮点击事件*/
switch (b.index) {
case 0:
break;
case 1:
vm.getImg()
break;
case 2:
galleryImg();/*打开相册*/
break;
default:
break;
}
})
}
},
// 调起相机
getImg () {
let vm = this
var c = plus.camera.getCamera();
c.captureImage(function(e) {
plus.io.resolveLocalFileSystemURL(e, function(entry) {
var imgSrc = entry.toLocalURL() + "?version=" + new Date().getTime(); //拿到图片路径
// 其他操作,比如预览展示
vm.compressImage(imgSrc)
}, function(e) {
console.log("读取拍照文件错误:" + e.message);
});
}, function(s) {
console.log("error" + s);
}, {
filename: "_doc/camera/"
})
},
// 图片转成base64
getBase64(img){
function getBase64Image(img,width,height) {
var canvas = document.createElement("canvas");
canvas.width = width ? width : img.width;
canvas.height = height ? height : img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL("image/jpeg", 0.3);
return dataURL;
}
var image = new Image();
image.crossOrigin = '';
image.src = img;
var deferred=$.Deferred();
if(img){
image.onload =function (){
deferred.resolve(getBase64Image(image));
}
return deferred.promise();
}
},
// 文件上传
upload (file) {
let formData = new FormData()
formData.append('fileIO', file)
this.service.post('file/uplode', formData).then(res => {
console.log(JSON.stringify(res.data))
})
},
// 图片转成base64
imageToBase64 (file) {
this.getBase64(file).then(res => {
var imgFile = this.dataURLtoFile(res,"img.png")
this.upload(imgFile)
})
},
// 压缩图片
compressImage(f){
let vm = this
plus.zip.compressImage({
src:f,
dst:"_doc/cm.jpg",
quality: 20,
overwrite:true,
width:'50%',
height:"50%"// 缩小到原来的一半
},
function(i){
console.log(i.size)
vm.imageToBase64(i.target,f[0].name);
})
},
// base64 转成file文件
dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
},
MUI 调起手机相机拍照压缩转成base64并上传
最新推荐文章于 2024-03-25 14:14:05 发布