图片尺寸比例和大小校验
2023-12-13 本文已影响0人
芸芸众生ing
function getImageFileInfo(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onerror = (e) => {
console.error('读取异常')
reject(false)
}
reader.onloadend = (e) => {
let image = new Image();
image.src = e.target.result;
image.onload = () => resolve([image, e.target.result])
}
reader.readAsDataURL(file);
})
}
function getImageSizeCheck(image, option) {
function gcd(a, b) {
if (b == 0) return a;
return gcd(b, a % b)
}
const { width = 1920, height = 1080, size = 10240, ratio = 0.15 } = option || {};
const { width: w, height: h, size: s } = image;
const imgRatio = w / h; // 图片尺寸比例
const optRatio = width / height; // 预设尺寸比例
let msg = '';
if (size < s) msg = `图片需小于${size}KB,`;
if (imgRatio > optRatio + ratio && imgRatio < optRatio - ratio) msg += `图片尺寸需符合${w}*${h}或${w / gys(w, h)}:${h / gys(w, h)}比例`;
if (msg) throw new Error(msg);
return true;
}
function gys(...args) {
const [item, ...rest] = args;
if (rest.length < 1) return a;
if (rest.length === 1) {
let a = item, b = rest[0];
while (a > 0 && b > 0 && a != b) {
if (a > b) a -= b;
else b -= a;
}
return a
}
return gys(item, gys(...rest))
}
const [image, img] = await getImageFileInfo(file);
getImageSizeCheck(image, { size: 1024, width: 1920, height: 1080 })