const gm = require('gm').subClass({ imageMagick: true }); const fs = require('fs'); const runExtnames = ["png", "jpg", "jpeg", "gif", "bmp"] // 检查格式是否符合 const extnameCheck = name => ~runExtnames.indexOf(name.toLocaleLowerCase()) /** * 对图片进行缩放 * @param {*} width Number 缩放宽度 * height Number 缩放高度 */ function zoom({ width, height }) { let seft = this width = Number(width) || 0; width = width < 0 ? 0 : width; height = Number(height) || 0; height = height < 0 ? 0 : height; if (!width && !height) throw 'Invalid zoom size' if (width && height) { let { origin_width: oWdith, origin_height: oHeight } = seft let porp = width / height, oPorp = oWdith / oHeight, left, top, cWidth, cHeight; if (oPorp <= porp) { seft.resize(width); cWidth = width; cHeight = cWidth / oPorp; } else if (oPorp > porp) { seft.resize(undefined, height); cHeight = height; cWidth = cHeight * oPorp; } left = (cWidth - width) / 2; top = (cHeight - height) / 2; seft = seft.crop(width, height, left, top); } else { seft = seft.resize(width || undefined, height || undefined); } return seft; } /** * 初始化缩略图对象 * @param {*} fileUri string 要进行缩放的图片本地路径 * stream readStream 要进行缩放的图片的可读流 * fileFormat string 要缩放的图片的后缀名 * @return Promise */ const init = ({ fileUri, stream }) => { if (fileUri) { stream = fs.createReadStream(fileUri); } else if (!stream) { throw 'Unknown file'; } return new Promise((resolve, reject) => { gm(stream).size({ bufferStream: true }, function (err, val) { if (err) { reject(err) } else { let result = Object.create(this); result.origin_width = val.width; result.origin_height = val.height; result.zoom = zoom; resolve(result); } }); }); } module.exports = exports = { runExtnames, init, extnameCheck };