export function chooseImage(sourceType = 'album') {
return new Promise((resolve, reject) => {
uni.chooseImage({
count: 1, // 最多可以选择的图片张数,默认9
sizeType: ['compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: [sourceType], // album 从相册选图,camera 使用相机,默认二者都有
success: ({ tempFilePaths }) => {
const tempFilePath = tempFilePaths[0];
resolve(tempFilePath)
},
fail: (err) => {
console.warn("chooseImage", err);
reject(err)
}
})
})
}
export function compressImage(src, quality = 80) {
return new Promise((resolve, reject) => {
uni.compressImage({
src: src, // 图片路径,图片的路径,可以是相对路径、临时文件路径、存储文件路径
quality: quality, // 压缩质量,范围0~100,数值越小,质量越低,压缩率越高(仅对jpg有效)
success: ({ tempFilePath }) => {
resolve(tempFilePath);
},
fail: (err) => {
console.warn("compressImage", err);
reject(err)
}
})
})
}
export function urlToBase64(url, extension = 'png') {
return new Promise((resolve, reject) => {
uni.request({
url: url,
method: 'GET',
responseType: 'arraybuffer',
success: (res) => {
let base64 = uni.arrayBufferToBase64(res.data);
let base64Url = `data:image/${extension};base64,${base64}`;
resolve(base64Url);
},
fail: (err) => {
console.warn("urlToBase64", err);
reject(err)
}
})
})
}
/**
* @param {String} sourceType: album 从相册选图,camera 使用相机,
* @param {Number} quality 压缩质量,范围0~100,数值越小,质量越低,压缩率越高(仅对jpg有效)
* @param {String} extension 拓展名 png jpg
*/
export default function chooseImageToBase64(sourceType = 'album', quality = 80, extension = 'png') { //
return new Promise((resolve, reject) => {
chooseImage(sourceType).then(tempFilePath => {
compressImage(tempFilePath, quality).then(tempFilePath => {
urlToBase64(tempFilePath, extension).then(base64 => {
resolve(base64)
})
})
})
})
}
网友评论