34 lines
882 B
TypeScript
34 lines
882 B
TypeScript
export async function getTextColorOnImage(url) {
|
|
let canvas
|
|
const width = 100
|
|
const height = 50
|
|
try {
|
|
// 1. 创建离屏Canvas
|
|
canvas = wx.createOffscreenCanvas({ type: '2d', width, height })
|
|
const ctx = canvas.getContext('2d')
|
|
|
|
// 2. 加载图片
|
|
const img = canvas.createImage()
|
|
await new Promise((resolve) => {
|
|
img.onload = resolve
|
|
img.src = url
|
|
})
|
|
|
|
// 3. 绘制并分析图像
|
|
ctx.drawImage(img, 0, 0, width, height)
|
|
|
|
// TODO: 增加取样,提高精确性
|
|
const pixelData = ctx.getImageData(10, 10, 1, 1).data
|
|
|
|
// 4. 计算文字颜色
|
|
const brightness = (pixelData[0] * 2126 + pixelData[1] * 7152 + pixelData[2] * 722) / 10000
|
|
return { textColor: brightness > 128 ? 'black' : 'white' }
|
|
} finally {
|
|
// 释放资源
|
|
if (canvas) {
|
|
canvas.width = 0;
|
|
canvas.height = 0;
|
|
}
|
|
}
|
|
}
|