-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
113 lines (89 loc) · 3.24 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const jimp = require('jimp');
const File = require('vinyl');
const PluginError = require('plugin-error');
const path = require('path');
const Transform = require('stream').Transform;
const PLUGIN_NAME = 'StubImage';
const loadFont = jimp.loadFont(jimp.FONT_SANS_128_BLACK);
function getMimeType(extension) {
extension = extension.substr(1).toLowerCase();
switch (extension) {
case 'jpeg':
case 'jpg':
return jimp.MIME_JPEG;
case 'png':
return jimp.MIME_PNG;
}
return null;
}
function fillImage(image, color) {
image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, offset) {
this.bitmap.data.writeUInt32BE(color, offset);
});
}
/**
* @param font
* @param {string} text
*/
function measureText(font, text) {
const w = jimp.measureText(font, text);
const h = jimp.measureTextHeight(font, text, w + 10);
return [w, h];
}
class StubImageTransform extends Transform {
/**
* @param {File} file
* @param {string=} encoding
* @param {function(Error, object)} callback
* @private
*/
_transform(file, encoding, callback) {
if (file.isNull()) {
callback(null, file);
} else if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams not supported!'));
} else if (file.isBuffer()) {
const extension = path.extname(path.basename(file.path));
const mimeType = getMimeType(extension);
if (!mimeType) {
this.emit('error', new PluginError(PLUGIN_NAME, 'File type not supported'));
return;
}
jimp.read(file.contents).then(async image => {
const w = image.bitmap.width;
const h = image.bitmap.height;
fillImage(image, 0xE5E5E5FF);
if (w >= 32 && h >= 16) {
const text = `${w}x${h}`;
const font = await loadFont;
const [textW, textH] = measureText(font, text);
const textImage = new jimp(textW, textH);
textImage.print(font, 0, 0, text);
textImage.color([
{apply: 'red', params: [128]},
{apply: 'green', params: [128]},
{apply: 'blue', params: [128]}
]);
const scaleFactor = Math.min(1, (w * .8) / textW, (h * .8) / textH);
const textNewW = Math.round(textW * scaleFactor);
const textNewH = Math.round(textH * scaleFactor);
textImage.resize(textNewW, textNewH);
image.composite(
textImage,
Math.round(w / 2 - textNewW / 2),
Math.round(h / 2 - textNewH / 2)
);
}
image.getBuffer(mimeType, (error, buffer) => {
file.contents = buffer;
callback(error, file);
});
}).catch(error => {
callback(error, file);
});
}
}
}
module.exports = function() {
return new StubImageTransform({objectMode: true});
};