you-yuan-uni-ui
Version:
you-yuan-uni-ui 组件库
269 lines (260 loc) • 7.96 kB
JavaScript
/**
* 压缩图片
* @param {Object} file { path: '', size: '' }
* @param {Number} limitSize 压缩目标 MB
*/
export const imgCompress = {
MB: 1024 * 1024,
// 获取可使用窗口宽度(提前使用uni.getSystemInfo获取PageWidth存在globalData)
rpxToPx(number) {
return (number / 750) * getApp({ allowDefault: true }).globalData.PageWidth;
},
// 获取文件信息
getFileInfo(path) {
return new Promise((resolve, reject) => {
// #ifdef MP-WEIXIN
uni.getFileSystemManager().getFileInfo({
filePath: path,
success: (res) => {
console.log('File Size =>', `${res.size / this.MB}MB`);
resolve(res.size);
},
fail: () => reject(null)
});
// #endif
// #ifndef MP-WEIXIN
uni.getFileInfo({
filePath: path,
success: (res) => {
console.log('File Size =>', `${res.size / this.MB}MB`);
resolve(res.size);
},
fail: () => reject(null)
});
// #endif
});
},
// 获取图片信息
getImageInfo(path) {
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: path,
success: (res) => resolve(res),
fail: () => reject(null)
});
});
},
// 判断是否达到压缩目标
getCompressImage(file, limitSize, ref) {
if (file.size > this.MB * limitSize) {
return this.calcImaeg(file.path, limitSize, ref);
} else {
return file.url;
}
},
// 递归
async calcImaeg(url, limitSize, ref) {
const size = await this.getFileInfo(url);
if (size > this.MB * limitSize) {
const imageInfo = await this.getImageInfo(url);
var maxSide = Math.max(imageInfo.width, imageInfo.height);
var windowW = this.rpxToPx(750);
var scale = 1;
if (maxSide > windowW) {
scale = windowW / maxSide;
}
var imageW = Math.floor(imageInfo.width * scale);
var imageH = Math.floor(imageInfo.height * scale);
const newPath = await this.getCanvasImage(url, imageW, imageH, ref);
return this.calcImaeg(newPath, limitSize, ref);
} else {
return url;
}
},
// 绘画
getCanvasImage(imagePath, imageW, imageH, ref) {
const context = this;
const pages = getCurrentPages();
const contextRef = pages[pages.length - 1];
const canvas = uni.createCanvasContext('imgCanvas', ref);
console.log(contextRef);
console.log(ref);
return new Promise((resolve, reject) => {
console.log(canvas);
canvas.drawImage(imagePath, 0, 0, imageW, imageH);
canvas.draw(
false,
(() => {
let canvasId;
// #ifdef H5
canvasId = canvas.id;
// #endif
// #ifndef H5
canvasId = canvas.canvasId;
// #endif
console.log('进入绘制回调', canvasId);
uni.canvasToTempFilePath({
canvasId: canvasId,
// canvas: canvas,
x: 0,
y: 0,
width: imageW,
height: imageH,
quality: 1,
success: (res) => {
console.log(res);
resolve(res.tempFilePath);
},
fail: (err) => {
console.log(err);
reject(imagePath);
},
complete(res) {
console.log(res);
}
});
// const query = uni.createSelectorQuery().in(ref).select('#' + canvasId)
// query.fields({ size: true, node: true, }, (res) => {
// console.log(res)
// const canvas = res.node;
// const ctx = canvas.getContext('2d');
// ctx.draw(false, () => {
// // uni.canvasToTempFilePath({
// // canvasId: canvasId,
// // canvas: canvas,
// // success: (res) => {
// // console.log('filepath', res
// // .tempFilePath);
// // ctx.draw();
// // }
// // }, this)
// uni.canvasToTempFilePath({
// canvasId: canvasId,
// canvas: canvas,
// x: 0,
// y: 0,
// width: imageW,
// height: imageH,
// quality: 1,
// success: (res) => {
// console.log(res)
// resolve(res.tempFilePath)
// },
// fail: (err) => {
// console.log(err)
// reject(imagePath)
// }
// })
// })
// }).exec()
})()
);
});
}
};
export function mpImgCompress(tempFilePath, quality = 50) {
return new Promise((resolve, reject) => {
// #ifdef H5
resolve(tempFilePath);
// #endif
// #ifndef H5
uni.compressImage({
src: tempFilePath,
quality: quality,
success: (res) => {
console.log(tempFilePath, res);
resolve(res.tempFilePath);
}
});
// #endif
});
}
export function checkSizeAndCompressImage(file) {
return new Promise(async (resolve, reject) => {
if (!file.fileType || file.fileType != 'image') {
resolve(file.tempFilePath);
} else {
// #ifdef H5
resolve(file.tempFilePath);
// #endif
// #ifndef H5
let finalUrl = '';
const m1 = 1024 * 1024;
if (file.size < m1 * 0.75) {
resolve(file.tempFilePath);
} else {
const q = parseInt(((m1 * 0.75) / file.size) * 100);
compressImage(file.tempFilePath, q).then((res) => {
resolve(res);
});
}
// #endif
}
});
}
// 压缩前将file转换成img对象
function readImg(file) {
return new Promise((resolve, reject) => {
const img = new Image();
const reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result;
};
reader.onerror = function (e) {
reject(e);
};
reader.readAsDataURL(file);
img.onload = function () {
resolve(img);
};
img.onerror = function (e) {
reject(e);
};
});
}
/**
* 压缩图片
* @param img 被压缩的img对象
* @param type 压缩后转换的文件类型
* @param mx 触发压缩的图片最大宽度限制
* @param mh 触发压缩的图片最大高度限制
*/
function compressImg(img, type, mx = 800, mh = 600) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const { width: originWidth, height: originHeight } = img;
// 最大尺寸限制
const maxWidth = mx;
const maxHeight = mh;
// 目标尺寸
let targetWidth = originWidth;
let targetHeight = originHeight;
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > 1) {
// 宽图片
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
// 高图片
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片绘制
context.drawImage(img, 0, 0, targetWidth, targetHeight);
canvas.toBlob(function (blob) {
// resolve(blob)
resolve(URL.createObjectURL(blob));
}, type || 'image/png');
});
}
// doCompressImg 压缩图片
export async function H5compressImg(file, w = 800, h = 600) {
const img = await readImg(file);
const blob = await compressImg(img, file.type, w, h);
return blob;
}