Path: blob/master/node_modules/@jimp/plugin-contain/src/index.js
1129 views
import { isNodePattern, throwError } from '@jimp/utils';12/**3* Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed.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 () => ({12contain(w, h, alignBits, mode, cb) {13if (typeof w !== 'number' || typeof h !== 'number') {14return throwError.call(this, 'w and h must be numbers', cb);15}1617// permit any sort of optional parameters combination18if (typeof alignBits === 'string') {19if (typeof mode === 'function' && typeof cb === 'undefined') cb = mode;20mode = alignBits;21alignBits = null;22}2324if (typeof alignBits === 'function') {25if (typeof cb === 'undefined') cb = alignBits;26mode = null;27alignBits = null;28}2930if (typeof mode === 'function' && typeof cb === 'undefined') {31cb = mode;32mode = null;33}3435alignBits =36alignBits ||37this.constructor.HORIZONTAL_ALIGN_CENTER |38this.constructor.VERTICAL_ALIGN_MIDDLE;39const hbits = alignBits & ((1 << 3) - 1);40const vbits = alignBits >> 3;4142// check if more flags than one is in the bit sets43if (44!(45(hbits !== 0 && !(hbits & (hbits - 1))) ||46(vbits !== 0 && !(vbits & (vbits - 1)))47)48) {49return throwError.call(50this,51'only use one flag per alignment direction',52cb53);54}5556const alignH = hbits >> 1; // 0, 1, 257const alignV = vbits >> 1; // 0, 1, 25859const f =60w / h > this.bitmap.width / this.bitmap.height61? h / this.bitmap.height62: w / this.bitmap.width;63const c = this.cloneQuiet().scale(f, mode);6465this.resize(w, h, mode);66this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(67x,68y,69idx70) {71this.bitmap.data.writeUInt32BE(this._background, idx);72});73this.blit(74c,75((this.bitmap.width - c.bitmap.width) / 2) * alignH,76((this.bitmap.height - c.bitmap.height) / 2) * alignV77);7879if (isNodePattern(cb)) {80cb.call(this, null, this);81}8283return this;84}85});868788