/* global plus:true */
/* eslint prefer-promise-reject-errors: "error" */
/*
拍照 = capture = readFile + saveInGallery
*
相册 = readFile
*
readFile = compress + checkSize + turnToFile
= 压缩》检查大小(this.maxSize)》转成File文件
*/
class UploadImg {
constructor () {
this.maxSize = 5 // 最大5M
this.quality = 20 // 1-100,越高图越大
}
capture () {
plus.nativeUI.showWaiting();
const _this = this
var cmr = plus.camera.getCamera();
// res分辨率
var res = cmr.supportedImageResolutions[0];
// fmt文件格式
var fmt = cmr.supportedImageFormats[0];
return new Promise((resolve, reject) => {
cmr.captureImage(function (p) {
Promise.all([_this.saveInGallery(p), resolve(_this.readFile(p))])
.then(() => plus.nativeUI.closeWaiting())
.catch(() => plus.nativeUI.closeWaiting())
},
function (error) {
reject(error)
plus.nativeUI.closeWaiting()
}, {
resolution: res,
format: fmt
})
})
}
gallery () {
plus.nativeUI.showWaiting();
const _this = this
return new Promise((resolve, reject) => {
plus.gallery.pick(
function (p) {
Promise.all([resolve(_this.readFile(p))])
.then(() => plus.nativeUI.closeWaiting())
.catch(() => plus.nativeUI.closeWaiting())
},
function (cancel) {
reject(cancel)
plus.nativeUI.closeWaiting()
}, {
filter: 'image'
}
)
})
}
saveInGallery (p) {
plus.gallery.save(p, function () {
console.log('保存进相册-成功')
},
function () {
console.log('保存进相册-失败')
})
}
compress (p) {
const _this = this
return new Promise((resolve, reject) => {
plus.zip.compressImage({
src: p,
dst: '_doc/compress.jpg',
overwrite: true,
quality: _this.quality
},
function (file) {
resolve(file.target)
},
function (error) {
console.log('压缩失败');
reject(error)
});
})
}
checkSize (size) {
const _this = this
return new Promise((resolve, reject) => {
const num = 1024;
const fileSize = (size / Math.pow(num, 2)).toFixed(2);
if (fileSize > _this.maxSize) {
plus.nativeUI.alert(`图片不得超过${_this.maxSize}M`);
reject(new Error('overSize'));
} else {
resolve()
}
})
}
readFile (p) {
const _this = this
return new Promise((resolve, reject) => {
this.compress(p).then((p) => {
plus.io.resolveLocalFileSystemURL(p, function (fs) {
fs.file(function (file) {
_this.checkSize(file.size)
.then(() => {
resolve(_this.turnToFile(fs, file))
})
.catch(error => {
console.log(error)
})
});
});
})
});
}
turnToFile (fs, oldFile) {
return new Promise((resolve, reject) => {
var reader = new plus.io.FileReader();
reader.readAsDataURL(oldFile)
reader.onloadend = function (e) {
// e.target.result
let data = e.target.result
// object专成file
let file = (function (path, name) {
let arr = path.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], name, {
type: mime
});
})(e.target.result, fs.name);
resolve({
data: data,
file: file
})
};
})
}
}
export const uploadImg = new UploadImg()
4***@qq.com
- 发布:2019-04-11 18:35
- 更新:2020-11-12 13:43
- 阅读:2851
2 个评论
要回复文章请先登录或注册
8***@qq.com
4***@qq.com (作者)