const path = require('path') const sharp = require('sharp'); const sharp1 = require('sharp'); const getSlide = async () => { const width = 334 const height = 140 const fragmentSize = 35 try { // 随机选择某个图片 const filePath = getRandomPath() //随机选择空缺部分的x y 坐标 const x = (Math.floor(Math.random() * 1000) % (width - 2 * fragmentSize)) + fragmentSize const y = Math.floor(Math.random() * 1000) % (height - fragmentSize) //获得大小图 const { image, fragment } = await createImage(filePath, width, height, fragmentSize, x, y) console.log(image,fragment) return { success: true, data: { image, fragment, x, y } } } catch (err) { return {success: false, msg: "服务器错误:" + err, data: null } } } function getRandomPath() { const fileLength = 2 const index = Math.floor(Math.random() * 1000) % fileLength return path.resolve(__dirname, `../static/images/${index + 1}.jpg`) } // 生成大图和小图,返回base64 function createImage(filePath, w, h, s, x, y) { return new Promise((resolve, reject) => { const res = {image: "", fragment: ""} const bg = `C:/Users/64616/WebstormProjects/验证码/koa/static/images/bg.jpg` sharp(filePath) .resize(w, h, "!")//调整成统一尺寸 .extract({left: x, top: y, width: s, height: s})//截取小图 .toBuffer() .then(imageData => { let data = imageData.toString('base64');//转换成base64的形式 res.fragment = "data:image/jpg;base64," + data sharp1(filePath).resize(w, h, "!") .composite([{input: bg, top: y, left: x, raw: {width: s, height: s, channels: 1}}]) //把与小图部分大小相同的灰色图片覆盖在大图上,形成大图空缺的样子 .toBuffer() .then(imageData => { let data = imageData.toString('base64'); res.image = "data:image/jpg;base64," + data resolve(res)//返回结果 }) .catch(error => { throw(error) }) }) .catch(error => { throw(error) }) }) } module.exports = { getSlide, check, }