async
function
extractImageParts(imagePath) {
const verifyImg = sharp(imagePath).extract({
left: 0,
top: 34,
width: 672,
height: 480 - 34,
});
const verifyList = [];
let
index = 1;
for
(
let
i = 0; i < 2; i++) {
for
(
let
j = 0; j < 3; j++) {
const left = j * 226;
const top = i * 226;
const task = verifyImg.extract({
left: left,
top: top,
width: 220,
height: 220,
});
const buf = await task.toBuffer();
fs.writeFileSync(`d:\\验证码\\${index}.jpg`, buf);
verifyList.push(buf);
index++;
}
}
return
verifyList;
}
async
function
calculateAverageColors(verifyList) {
return
await Promise.all(
verifyList.map(getAverageColor)
);
}
async
function
getAverageColor(buffer) {
const { data, info } = await sharp(buffer)
.resize({ width: 12, height: 12 })
.raw()
.toBuffer({ resolveWithObject:
true
});
let
totalR = 0, totalG = 0, totalB = 0;
for
(
let
i = 0; i < data.length; i += 3) {
totalR += data[i];
totalG += data[i + 1];
totalB += data[i + 2];
}
const numPixels = info.width * info.height;
return
[
Math.round(totalR / numPixels),
Math.round(totalG / numPixels),
Math.round(totalB / numPixels),
];
}