//路由 router.post('/uploadImg', upload.single('img'), async(ctx, next) => { // 图片压缩 let filename = ctx.req.file.filename; gm(process.cwd() + "/public/test/" + filename) .resize(1000, 1000, '>') //设置压缩后的w/h .setFormat('JPEG') .quality(70) //设置压缩质量: 0-100 .strip() .autoOrient() .write(process.cwd() + "/public/test/" + filename, function(err) { console.log("压缩失败", err) }) ctx.body = '/test/' + filename //返回文件名 })
Promise.mapSeries(this.subject, this.createTempWordFile.bind(this)) .then(wordsFiles => { return [wordsFiles, this.tempFile()] }).spread((wordsFiles, tempPath) => { const tempCaptcha = gm(wordsFiles.shift()).background('none') return tempCaptcha.append.apply(tempCaptcha, wordsFiles).append(true) .setFormat('png') .writeAsync(tempPath).return(tempPath) }).then(captchaPath => { return [captchaPath, this.createRandomLinesBackground()] }).spread((captchaPath, backgroundImagePath) => { return gm(backgroundImagePath) .composite(captchaPath) .geometry('+' + this.captchaWidth * .05 + '+0') .setFormat('png') })
/* * 图片转为webp格式(文件名中的_2x.会被替换) * @params {String} filepath: 图片所在目录; * @params {String} filename: 图片文件名; * @params {String} outpath: 输出目录; * @params {Function} callback: callback(可选); */ function toWebpImg (filepath, filename, outpath, callback) { let webpPath = path.join(outpath, filename.replace('_2x.', '.').split('.')[0] + '.webp'); gm(path.join(filepath, filename)) .setFormat('webp') .write(webpPath, err => { if (err) { Tip.error(err); return false; } Tip.safe(`${webpPath}生成成功。`, true); if (callback) callback(webpPath); }); }
this.tempFile().then(tempPath => { const wordLayer = gm(this.wordImgWidth, this.captchaHeight, 'transparent') .fontSize(this.fontSize) .fill(this.randColor()) .font(this.randFont()) .drawText(0, 0, word, 'Center') .setFormat('png') // 正常模式增加噪点和左右变形 if (recognitionDifficulty !== 'easy') { wordLayer.noise(this.randNoise()) .rotate('transparent', _.sample([1, -1]) * parseInt(Math.random() * 15, 10)) } if (recognitionDifficulty === 'hard') { wordLayer.affine([ _.random(.9, 1.1), _.random(-.1, .1), _.random(-.1, .1), _.random(.9, 1.1), _.random(-.2, .1), _.random(-.2, .1) ]).transform() } return wordLayer .resize(this.wordImgWidth, this.captchaHeight) .scale(this.wordImgWidth, this.captchaHeight) .writeAsync(tempPath) .return(tempPath) })
.setFormat('JPEG') .quality(70) //设置压缩质量: 0-100 .strip()