Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/node_modules/@jimp/plugin-contain/src/index.js
1129 views
1
import { isNodePattern, throwError } from '@jimp/utils';
2
3
/**
4
* Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed.
5
* @param {number} w the width to resize the image to
6
* @param {number} h the height to resize the image to
7
* @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment
8
* @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
9
* @param {function(Error, Jimp)} cb (optional) a callback for when complete
10
* @returns {Jimp} this for chaining of methods
11
*/
12
export default () => ({
13
contain(w, h, alignBits, mode, cb) {
14
if (typeof w !== 'number' || typeof h !== 'number') {
15
return throwError.call(this, 'w and h must be numbers', cb);
16
}
17
18
// permit any sort of optional parameters combination
19
if (typeof alignBits === 'string') {
20
if (typeof mode === 'function' && typeof cb === 'undefined') cb = mode;
21
mode = alignBits;
22
alignBits = null;
23
}
24
25
if (typeof alignBits === 'function') {
26
if (typeof cb === 'undefined') cb = alignBits;
27
mode = null;
28
alignBits = null;
29
}
30
31
if (typeof mode === 'function' && typeof cb === 'undefined') {
32
cb = mode;
33
mode = null;
34
}
35
36
alignBits =
37
alignBits ||
38
this.constructor.HORIZONTAL_ALIGN_CENTER |
39
this.constructor.VERTICAL_ALIGN_MIDDLE;
40
const hbits = alignBits & ((1 << 3) - 1);
41
const vbits = alignBits >> 3;
42
43
// check if more flags than one is in the bit sets
44
if (
45
!(
46
(hbits !== 0 && !(hbits & (hbits - 1))) ||
47
(vbits !== 0 && !(vbits & (vbits - 1)))
48
)
49
) {
50
return throwError.call(
51
this,
52
'only use one flag per alignment direction',
53
cb
54
);
55
}
56
57
const alignH = hbits >> 1; // 0, 1, 2
58
const alignV = vbits >> 1; // 0, 1, 2
59
60
const f =
61
w / h > this.bitmap.width / this.bitmap.height
62
? h / this.bitmap.height
63
: w / this.bitmap.width;
64
const c = this.cloneQuiet().scale(f, mode);
65
66
this.resize(w, h, mode);
67
this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
68
x,
69
y,
70
idx
71
) {
72
this.bitmap.data.writeUInt32BE(this._background, idx);
73
});
74
this.blit(
75
c,
76
((this.bitmap.width - c.bitmap.width) / 2) * alignH,
77
((this.bitmap.height - c.bitmap.height) / 2) * alignV
78
);
79
80
if (isNodePattern(cb)) {
81
cb.call(this, null, this);
82
}
83
84
return this;
85
}
86
});
87
88