Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/node_modules/@jimp/plugin-gaussian/src/index.js
1126 views
1
import { isNodePattern, throwError } from '@jimp/utils';
2
3
/**
4
* Applies a true Gaussian blur to the image (warning: this is VERY slow)
5
* @param {number} r the pixel radius of the blur
6
* @param {function(Error, Jimp)} cb (optional) a callback for when complete
7
* @returns {Jimp} this for chaining of methods
8
*/
9
export default () => ({
10
gaussian(r, cb) {
11
// http://blog.ivank.net/fastest-gaussian-blur.html
12
if (typeof r !== 'number') {
13
return throwError.call(this, 'r must be a number', cb);
14
}
15
16
if (r < 1) {
17
return throwError.call(this, 'r must be greater than 0', cb);
18
}
19
20
const rs = Math.ceil(r * 2.57); // significant radius
21
const range = rs * 2 + 1;
22
const rr2 = r * r * 2;
23
const rr2pi = rr2 * Math.PI;
24
25
const weights = [];
26
27
for (let y = 0; y < range; y++) {
28
weights[y] = [];
29
for (let x = 0; x < range; x++) {
30
const dsq = (x - rs) ** 2 + (y - rs) ** 2 ;
31
weights[y][x] = Math.exp(-dsq / rr2) / rr2pi;
32
}
33
}
34
35
for (let y = 0; y < this.bitmap.height; y++) {
36
for (let x = 0; x < this.bitmap.width; x++) {
37
let red = 0;
38
let green = 0;
39
let blue = 0;
40
let alpha = 0;
41
let wsum = 0;
42
43
for (let iy = 0; iy < range; iy++) {
44
for (let ix = 0; ix < range; ix++) {
45
const x1 = Math.min(this.bitmap.width - 1, Math.max(0, ix + x - rs ));
46
const y1 = Math.min(this.bitmap.height - 1, Math.max(0, iy + y - rs));
47
const weight = weights[iy][ix];
48
const idx = (y1 * this.bitmap.width + x1) << 2;
49
50
red += this.bitmap.data[idx] * weight;
51
green += this.bitmap.data[idx + 1] * weight;
52
blue += this.bitmap.data[idx + 2] * weight;
53
alpha += this.bitmap.data[idx + 3] * weight;
54
wsum += weight;
55
}
56
57
const idx = (y * this.bitmap.width + x) << 2;
58
59
this.bitmap.data[idx] = Math.round(red / wsum);
60
this.bitmap.data[idx + 1] = Math.round(green / wsum);
61
this.bitmap.data[idx + 2] = Math.round(blue / wsum);
62
this.bitmap.data[idx + 3] = Math.round(alpha / wsum);
63
}
64
}
65
}
66
67
if (isNodePattern(cb)) {
68
cb.call(this, null, this);
69
}
70
71
return this;
72
}
73
});
74
75