init
This commit is contained in:
1
src/libs/area.js
Normal file
1
src/libs/area.js
Normal file
File diff suppressed because one or more lines are too long
204
src/libs/faceValidator.js
Normal file
204
src/libs/faceValidator.js
Normal file
@@ -0,0 +1,204 @@
|
||||
import * as faceapi from 'face-api.js'
|
||||
|
||||
// 模型加载状态
|
||||
let modelsLoaded = false
|
||||
|
||||
/**
|
||||
* 加载 face-api.js 模型
|
||||
*/
|
||||
export async function loadFaceApiModels() {
|
||||
if (modelsLoaded) {
|
||||
console.log('Face API 模型已经加载过了')
|
||||
return true
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('开始加载 Face API 模型...')
|
||||
|
||||
// 获取基础路径,处理 vite 的 base 配置
|
||||
const basePath = import.meta.env.BASE_URL || '/'
|
||||
const modelsPath = basePath.endsWith('/') ? basePath + 'models' : basePath + '/models'
|
||||
|
||||
console.log('模型加载路径:', modelsPath)
|
||||
|
||||
// 加载必需的模型
|
||||
await Promise.all([
|
||||
faceapi.nets.tinyFaceDetector.loadFromUri(modelsPath),
|
||||
faceapi.nets.faceLandmark68Net.loadFromUri(modelsPath),
|
||||
faceapi.nets.faceRecognitionNet.loadFromUri(modelsPath)
|
||||
])
|
||||
|
||||
console.log('Face API 模型加载完成')
|
||||
modelsLoaded = true
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('Face API 模型加载失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查模型是否已加载
|
||||
*/
|
||||
export function areModelsLoaded() {
|
||||
return modelsLoaded
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证图片中的人脸
|
||||
* @param {File} file - 图片文件
|
||||
* @returns {Promise<Object>} - 验证结果
|
||||
*/
|
||||
export async function validateFaceInImage(file) {
|
||||
// 如果模型未加载,先加载模型
|
||||
if (!modelsLoaded) {
|
||||
const loaded = await loadFaceApiModels()
|
||||
if (!loaded) {
|
||||
return {
|
||||
success: false,
|
||||
message: '人脸识别模型加载失败,请刷新页面重试'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const img = new Image()
|
||||
|
||||
img.onload = async () => {
|
||||
try {
|
||||
console.log('开始进行人脸检测...')
|
||||
|
||||
// 使用 TinyFaceDetector 进行人脸检测
|
||||
const detections = await faceapi
|
||||
.detectAllFaces(img, new faceapi.TinyFaceDetectorOptions({
|
||||
inputSize: 416,
|
||||
scoreThreshold: 0.3
|
||||
}))
|
||||
.withFaceLandmarks()
|
||||
|
||||
console.log(`检测到 ${detections.length} 张人脸`)
|
||||
|
||||
// 检查是否检测到人脸
|
||||
if (detections.length === 0) {
|
||||
resolve({
|
||||
success: false,
|
||||
message: '未检测到人脸,请上传包含清晰人脸的图片'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 检查是否只有一张人脸
|
||||
if (detections.length > 1) {
|
||||
resolve({
|
||||
success: false,
|
||||
message: '检测到多张人脸,请上传只包含一张人脸的图片'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const detection = detections[0]
|
||||
const confidence = detection.detection.score
|
||||
|
||||
console.log('人脸检测置信度:', confidence)
|
||||
|
||||
// 检查置信度是否足够高
|
||||
const minConfidence = 0.3 // 降低到 0.6 以提高通过率
|
||||
if (confidence < minConfidence) {
|
||||
resolve({
|
||||
success: false,
|
||||
message: `人脸清晰度不够(置信度: ${(confidence * 100).toFixed(1)}%),请上传更清晰的人脸图片`
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 检查人脸大小(相对于图片尺寸)
|
||||
const faceBox = detection.detection.box
|
||||
const imageArea = img.naturalWidth * img.naturalHeight
|
||||
const faceArea = faceBox.width * faceBox.height
|
||||
const faceRatio = faceArea / imageArea
|
||||
|
||||
console.log('人脸占图片比例:', (faceRatio * 100).toFixed(2) + '%')
|
||||
|
||||
const minFaceRatio = 0.01 // 降低到 1.5% 以提高通过率
|
||||
if (faceRatio < minFaceRatio) {
|
||||
resolve({
|
||||
success: false,
|
||||
message: '人脸在图片中占比太小,请上传人脸更大更清晰的图片'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 检查人脸角度(通过关键点判断)
|
||||
if (detection.landmarks) {
|
||||
const landmarks = detection.landmarks
|
||||
const leftEye = landmarks.getLeftEye()
|
||||
const rightEye = landmarks.getRightEye()
|
||||
|
||||
// 计算眼睛之间的角度来判断人脸是否正面
|
||||
if (leftEye.length > 0 && rightEye.length > 0) {
|
||||
const leftEyeCenter = leftEye[0]
|
||||
const rightEyeCenter = rightEye[3]
|
||||
|
||||
const eyeAngle = Math.abs(
|
||||
Math.atan2(
|
||||
rightEyeCenter.y - leftEyeCenter.y,
|
||||
rightEyeCenter.x - leftEyeCenter.x
|
||||
) * 180 / Math.PI
|
||||
)
|
||||
|
||||
console.log('人脸角度:', eyeAngle.toFixed(1) + '度')
|
||||
|
||||
const maxAngle = 30 // 放宽到 20 度
|
||||
if (eyeAngle > maxAngle) {
|
||||
resolve({
|
||||
success: false,
|
||||
message: '请上传正面人脸照片,避免侧脸或过度倾斜的角度'
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 所有验证通过
|
||||
resolve({
|
||||
success: true,
|
||||
message: `人脸验证通过(置信度: ${(confidence * 100).toFixed(1)}%)`,
|
||||
confidence: confidence,
|
||||
faceRatio: faceRatio,
|
||||
faceBox: {
|
||||
x: faceBox.x,
|
||||
y: faceBox.y,
|
||||
width: faceBox.width,
|
||||
height: faceBox.height
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('人脸检测过程中出错:', error)
|
||||
resolve({
|
||||
success: false,
|
||||
message: '人脸检测失败,请重试或更换图片'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
img.onerror = () => {
|
||||
resolve({
|
||||
success: false,
|
||||
message: '图片加载失败,请检查图片格式'
|
||||
})
|
||||
}
|
||||
|
||||
// 加载图片
|
||||
const reader = new FileReader()
|
||||
reader.onload = (e) => {
|
||||
img.src = e.target.result
|
||||
}
|
||||
reader.onerror = () => {
|
||||
resolve({
|
||||
success: false,
|
||||
message: '图片读取失败,请重试'
|
||||
})
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
29
src/libs/getUserPicture.js
Normal file
29
src/libs/getUserPicture.js
Normal file
@@ -0,0 +1,29 @@
|
||||
import { globalStore } from "@/globalstore";
|
||||
import { generateQR, Request } from "../libs/utils"
|
||||
import Haibao from "@/libs/haibao"
|
||||
import mask from "../assets/images/haibao-mask.webp"
|
||||
import haibaoCoverBorder from "../assets/images/haibao-cover.webp"
|
||||
|
||||
|
||||
export default async () => {
|
||||
let userUrl = globalStore.result_url
|
||||
|
||||
if (!userUrl) {
|
||||
const result = await Request('face/square', { my_only: 1, page: 1, per_page: 100 }, "GET", true)
|
||||
if (result.res.status === 200) {
|
||||
const dataHit = result.json.data.find(v => v.is_public)
|
||||
if (!dataHit) {
|
||||
return weui.alert("请先去参与打榜")
|
||||
}
|
||||
userUrl = dataHit.result_url
|
||||
}
|
||||
}
|
||||
|
||||
const haibaoCover = new Haibao(951, 1607)
|
||||
haibaoCover.add(userUrl, 0, 50, 951, 1698)
|
||||
haibaoCover.add(mask, 10, 100)
|
||||
haibaoCover.add(haibaoCoverBorder, 0, 0)
|
||||
|
||||
await haibaoCover.draw('destination-in');
|
||||
return await haibaoCover.generate({ mimeType: 'image/png' });
|
||||
}
|
||||
119
src/libs/haibao.js
Normal file
119
src/libs/haibao.js
Normal file
@@ -0,0 +1,119 @@
|
||||
export default class Haibao {
|
||||
constructor(width, height, color = '#fff') {
|
||||
this.canvas = document.createElement('canvas');
|
||||
this.ctx = this.canvas.getContext('2d', { alpha: true });
|
||||
this.canvas.width = width;
|
||||
this.canvas.height = height;
|
||||
// this.ctx.fillStyle = color;
|
||||
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
|
||||
|
||||
this.zIndex = 0
|
||||
this.imagePromises = []
|
||||
this.images = []; // 存储待合成的图片信息
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加图片到合成队列(现在返回Promise)
|
||||
* @param {string|HTMLImageElement} image 图片URL或Image对象
|
||||
* @param {number} x 绘制X坐标
|
||||
* @param {number} y 绘制Y坐标
|
||||
* @returns {Promise} 图片加载完成的Promise
|
||||
*/
|
||||
add (image, x, y, width = 'auto', height = 'auto', index) {
|
||||
this.zIndex++
|
||||
const zIndex = index ? index : this.zIndex
|
||||
const loadPromise = this._createLoadPromise(image).then(img => {
|
||||
this.images.push({ img, x, y, width, height, zIndex });
|
||||
});
|
||||
|
||||
this.imagePromises.push(loadPromise);
|
||||
return loadPromise;
|
||||
}
|
||||
text (text, x, y, opts) {
|
||||
const { font = '16px sans-serif', color = '#000', align = 'center' } = opts || {};
|
||||
this.ctx.font = font;
|
||||
this.ctx.fillStyle = color;
|
||||
|
||||
const drawText = (text, x, y) => {
|
||||
this.ctx.fillText(text, x, y);
|
||||
};
|
||||
const totalWidth = this.ctx.measureText(text).width;
|
||||
|
||||
if (align === 'center') {
|
||||
x -= totalWidth / 2;
|
||||
}
|
||||
|
||||
drawText(text, x, y);
|
||||
|
||||
return this
|
||||
}
|
||||
async draw (mask = 'source-over') {
|
||||
await Promise.all(this.imagePromises);
|
||||
|
||||
// 绘制所有图片
|
||||
this.images.sort((a, b) => a.zIndex - b.zIndex)
|
||||
this.images.forEach(({ img, x, y, width, height, zIndex }, idx) => {
|
||||
const w = width === 'auto' ? img.width : width
|
||||
const h = height === 'auto' ? img.height : height
|
||||
this.ctx.drawImage(img, x, y, w, h);
|
||||
if (idx === 0) {
|
||||
this.ctx.globalCompositeOperation = mask
|
||||
} else {
|
||||
this.ctx.globalCompositeOperation = 'source-over'
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 生成合成后的图片(返回Promise)
|
||||
* @returns {Promise<string>} 合成后的Base64图片数据
|
||||
*/
|
||||
async generate ({ mimeType = 'image/jpeg', quality = .8 }) {
|
||||
const validTypes = ['image/png', 'image/jpeg', 'image/webp'];
|
||||
mimeType = validTypes.includes(mimeType) ? mimeType : 'image/png';
|
||||
quality = Math.min(1, Math.max(0, Number(quality))) || .8;
|
||||
|
||||
const b64 = this.canvas.toDataURL(mimeType, quality)
|
||||
|
||||
this.images.length = 0;
|
||||
this.imagePromises.length = 0;
|
||||
|
||||
return b64
|
||||
|
||||
}
|
||||
|
||||
// 创建加载Promise(私有方法)
|
||||
_createLoadPromise (image) {
|
||||
if (typeof image === 'string') {
|
||||
return this._loadImageFromUrl(image);
|
||||
} else if (image instanceof HTMLImageElement) {
|
||||
return this._handleExistingImage(image);
|
||||
}
|
||||
return Promise.reject(new Error('Invalid image type'));
|
||||
}
|
||||
|
||||
// 从URL加载图片
|
||||
_loadImageFromUrl (url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.crossOrigin = 'anonymous';
|
||||
img.src = url;
|
||||
img.onload = () => resolve(img);
|
||||
img.onerror = reject;
|
||||
});
|
||||
}
|
||||
|
||||
// 处理已存在的Image对象
|
||||
_handleExistingImage (img) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (img.complete && img.naturalHeight !== 0) {
|
||||
resolve(img);
|
||||
} else {
|
||||
img.onload = () => resolve(img);
|
||||
img.onerror = reject;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
221
src/libs/utils.js
Normal file
221
src/libs/utils.js
Normal file
@@ -0,0 +1,221 @@
|
||||
import QRCode from "qrcode"
|
||||
export const HOST = "https://huodong2.lzlj.com"
|
||||
export const DIR = "zhaoma"
|
||||
export const API = `${HOST}/api/${DIR}/`
|
||||
export const debuglog = (text) => {
|
||||
console.log(`%c -- ${text} `, "background:green;color:#fff")
|
||||
}
|
||||
export const Storage = {
|
||||
set (name, data) {
|
||||
localStorage.setItem(name, JSON.stringify(data))
|
||||
},
|
||||
get (name) {
|
||||
return JSON.parse(localStorage.getItem(name))
|
||||
},
|
||||
clear () {
|
||||
localStorage.clear()
|
||||
},
|
||||
remove (name) {
|
||||
localStorage.removeItem(name)
|
||||
}
|
||||
}
|
||||
export const Sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
export const isLogin = () => {
|
||||
return !!(Storage.get("userinfos") && Storage.get("userinfos").phone)
|
||||
// return true
|
||||
}
|
||||
export const isBaseLogin = () => {
|
||||
return Storage.get("userinfos")
|
||||
// return true
|
||||
}
|
||||
export const generateQR = async (text, width = 160, height = 160) => {
|
||||
return await QRCode.toDataURL(`${HOST}/${DIR}/?${text}`, {
|
||||
errorCorrectionLevel: 'H',
|
||||
width: width,
|
||||
height: height,
|
||||
margin: 1,
|
||||
colorDark: "#000000",
|
||||
colorLight: "#e8e2cc",
|
||||
})
|
||||
}
|
||||
|
||||
export const createPop = (id, classname) => {
|
||||
const wrapper = document.createElement("div")
|
||||
wrapper.id = id
|
||||
wrapper.classList.add(classname)
|
||||
document.querySelector("body").appendChild(wrapper)
|
||||
return wrapper
|
||||
}
|
||||
export const isIos = () => {
|
||||
return /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)
|
||||
}
|
||||
export const isWeixin = () => {
|
||||
return /MicroMessenger/i.test(window.navigator.userAgent)
|
||||
}
|
||||
export const isWeixinPlatform = () => {
|
||||
return /MicroMessenger/i.test(window.navigator.userAgent) || window.__wxjs_environment === 'miniprogram'
|
||||
}
|
||||
export const isWeibo = () => {
|
||||
return /Weibo/i.test(window.navigator.userAgent)
|
||||
}
|
||||
export const isDouyin = () => {
|
||||
return /aweme/i.test(window.navigator.userAgent)
|
||||
}
|
||||
export const isWebp = () => {
|
||||
return !![].map && document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0
|
||||
}
|
||||
export const isMiniPage = () => {
|
||||
return window.__wxjs_environment === 'miniprogram'
|
||||
// return true
|
||||
}
|
||||
export const webpAsPng = (url) => {
|
||||
const nowebp = document.querySelector("html").classList.value.indexOf("nowebp") > -1
|
||||
return nowebp ? url.replace(".webp", ".webp").replace("images/", "images/png/") : url
|
||||
}
|
||||
export const getUserBrowersName = () => {
|
||||
const ua = navigator.userAgent
|
||||
if (isWeixin()) {
|
||||
return "weixin"
|
||||
} else if (isWeibo()) {
|
||||
return "weibo"
|
||||
} else if (isDouyin()) {
|
||||
return "douyin"
|
||||
} else if (isMiniPage()) {
|
||||
return "miniprogram"
|
||||
} else {
|
||||
return "other"
|
||||
}
|
||||
}
|
||||
export const getMiniPageBtnHack = (url) => {
|
||||
//TODO确认小程序appid!!!
|
||||
let html = ''
|
||||
html += `<wx-open-launch-weapp id="launch-btn" appid="wxc911dd6c6bc128de" path="${url}"><template>`
|
||||
html += '<style>.open-btn {position:absolute;width:100%;height:100%;opacity:0}</style>'
|
||||
html += '<button class="open-btn">打开小程序</button>'
|
||||
html += '</template></wx-open-launch-weapp>'
|
||||
return html
|
||||
}
|
||||
|
||||
export const miniJumpToScene = () => {
|
||||
wx.miniProgram.navigateTo({ url: '/pages/unify/unify?orgId=200282401019674482&targetUrl=%2Fpages%2Fretail%2Forder%2Forder-list%3Ftab%3DAll%26topTab%3D1' })
|
||||
}
|
||||
export const miniJumpToActive = () => {
|
||||
wx.miniProgram.navigateTo({ url: '/pages/retail-act/landing-page/ordinary?id=897432916524553363&orgId=200282401019674482&programId=84796583983972352' })
|
||||
}
|
||||
export const miniJumpToCouopon = () => {
|
||||
wx.miniProgram.navigateTo({
|
||||
url: '/pages/unify/unify?orgId=200282401019674482&targetUrl=%2Fpages%2Fcoupon%2Fcoupons-list'
|
||||
})
|
||||
}
|
||||
export const miniJumpToCenter = () => {
|
||||
wx.miniProgram.navigateTo({ url: '/pages/unify/unify?currentCode=my&orgId=200282401019674482' })
|
||||
}
|
||||
//[ ]
|
||||
// export const miniJumpToCouopon = () => {
|
||||
// wx.miniProgram.navigateTo({ url: 'pages/unify/unify?orgId=200282401019674482&targetUrl=%2Fpages%2Fcoupon%2Fcoupons-list' })
|
||||
// }
|
||||
export const getParam = (name) => {
|
||||
if ('URLSearchParams' in window) {
|
||||
var params = new URLSearchParams(window.location.search)
|
||||
return params.get(name) ? params.get(name) : null
|
||||
} else {
|
||||
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'),
|
||||
r = window.location.search.substr(1).match(reg)
|
||||
|
||||
if (r != null) return unescape(r[2])
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const Request = async (url, data, type, noloading, noerror) => {
|
||||
let headers = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: "application/json",
|
||||
"Source": "iceSip",
|
||||
'App-Channel': getUserBrowersName(),
|
||||
refer: document.referrer,
|
||||
blackbox: Storage.get("blackbox") ? Storage.get("blackbox") : false
|
||||
}
|
||||
|
||||
if (url != "sms/sendCode" && url != "sms/authPhone" && url != "wechat/login" && url != "wechat/jssdk") {
|
||||
if (isLogin()) {
|
||||
headers.Authorization = `Bearer ${Storage.get("userinfos").api_token}`
|
||||
} else {
|
||||
Storage.clear()
|
||||
weui.alert("登录失效,请重新登录")
|
||||
// window.location.reload()
|
||||
}
|
||||
}
|
||||
|
||||
if (isBaseLogin() && url == "sms/authPhone") {
|
||||
headers.Authorization = `Bearer ${Storage.get("userinfos").api_token}`
|
||||
}
|
||||
|
||||
let loading = false
|
||||
if (!noloading) {
|
||||
loading = weui.loading()
|
||||
}
|
||||
|
||||
let message = "请求失败,请重试"
|
||||
|
||||
let fetchData = {
|
||||
method: type || 'POST',
|
||||
headers: new Headers(headers),
|
||||
}
|
||||
|
||||
if (fetchData.method == "POST") {
|
||||
fetchData.body = JSON.stringify(data)
|
||||
}
|
||||
|
||||
let requrl = `${API}${url}`
|
||||
|
||||
if (type === "GET") {
|
||||
let paramArr = []
|
||||
Object.keys(data).forEach(v => {
|
||||
paramArr.push(`${v}=${data[v]}`)
|
||||
})
|
||||
requrl = paramArr.length === 0 ? `${requrl}` : `${requrl}?${paramArr.join("&")}`
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${requrl}`, fetchData)
|
||||
const result = await response.json()
|
||||
message = result.message || message
|
||||
if (getParam("debug")) {
|
||||
console.log("url:", url)
|
||||
console.log("data:", data)
|
||||
console.log(response)
|
||||
console.log(result)
|
||||
}
|
||||
|
||||
loading && loading.hide()
|
||||
|
||||
if (response.status == 200 || response.status == 201) {
|
||||
return { res: response, json: result }
|
||||
} else if (response.status == 401) {
|
||||
Storage.clear()
|
||||
weui.alert("登录失效,请重新登录")
|
||||
// window.location.reload()
|
||||
return
|
||||
} else {
|
||||
if (!noerror) {
|
||||
// weui.alert(message)
|
||||
}
|
||||
return { res: response, json: result }
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
if (!noerror) {
|
||||
// weui.alert(message)
|
||||
}
|
||||
loading && loading.hide()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// let str = ''
|
||||
// let s = ''
|
||||
// for (let index = 0; index < 60; index++) {
|
||||
// str += `import denglong2${index} from "./images/frame/denglong2/denglong2_${index}.webp";`
|
||||
// s+=`denglong2${index},`
|
||||
// }
|
||||
Reference in New Issue
Block a user