Path: blob/master/node_modules/@jimp/plugin-cover/src/index.js
1129 views
import { isNodePattern, throwError } from '@jimp/utils';12/**3* Scale the image so the given width and height keeping the aspect ratio. Some parts of the image may be clipped.4* @param {number} w the width to resize the image to5* @param {number} h the height to resize the image to6* @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment7* @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)8* @param {function(Error, Jimp)} cb (optional) a callback for when complete9* @returns {Jimp} this for chaining of methods10*/11export default () => ({12cover(w, h, alignBits, mode, cb) {13if (typeof w !== 'number' || typeof h !== 'number') {14return throwError.call(this, 'w and h must be numbers', cb);15}1617if (18alignBits &&19typeof alignBits === 'function' &&20typeof cb === 'undefined'21) {22cb = alignBits;23alignBits = null;24mode = null;25} else if (typeof mode === 'function' && typeof cb === 'undefined') {26cb = mode;27mode = null;28}2930alignBits =31alignBits ||32this.constructor.HORIZONTAL_ALIGN_CENTER |33this.constructor.VERTICAL_ALIGN_MIDDLE;34const hbits = alignBits & ((1 << 3) - 1);35const vbits = alignBits >> 3;3637// check if more flags than one is in the bit sets38if (39!(40(hbits !== 0 && !(hbits & (hbits - 1))) ||41(vbits !== 0 && !(vbits & (vbits - 1)))42)43)44return throwError.call(45this,46'only use one flag per alignment direction',47cb48);4950const alignH = hbits >> 1; // 0, 1, 251const alignV = vbits >> 1; // 0, 1, 25253const f =54w / h > this.bitmap.width / this.bitmap.height55? w / this.bitmap.width56: h / this.bitmap.height;57this.scale(f, mode);58this.crop(59((this.bitmap.width - w) / 2) * alignH,60((this.bitmap.height - h) / 2) * alignV,61w,62h63);6465if (isNodePattern(cb)) {66cb.call(this, null, this);67}6869return this;70}71});727374