-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
144 lines (128 loc) · 5.34 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
const chalk = require('chalk');
const gutil = require('gulp-util');
const path = require('path');
const plur = require('plur');
const sharp = require('sharp');
const through = require('through2-concurrent');
const async = require('async');
const PLUGIN_NAME = require('./package.json').name;
const VALID_EXTS = ['.png'];
/**
* Wrap image and luminance mask in a ZorroSVG file.
* @see https://github.com/Quasimondo/QuasimondoJS/blob/ce7ffb317f7435940046d5ff46a7503f92efd328/zorrosvg/js/zorrosvgmaskmaker.js#L400-L449
* @param {Buffer} buffer
* @param {Object} params {cwd, base, path, width, height}
* @return {Buffer}
*/
function getSvg(buffer, params) {
return new gutil.File({
cwd: params.cwd,
base: params.base,
path: params.path.replace('.png', '.svg'),
contents: Buffer.from(`<svg width="${params.width}" height="${params.height / 2}" viewBox="0 0 ${params.width} ${params.height / 2}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<filter id="zorrosvg" primitiveUnits="objectBoundingBox" color-interpolation-filters="sRGB">
<feOffset in="SourceGraphic" result="bottom-half" dy="-0.5"></feOffset>
<feColorMatrix type="matrix" in="bottom-half" result="luma-mask" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0"></feColorMatrix>
<feComposite in="SourceGraphic" in2="luma-mask" operator="in"></feComposite>
</filter>
</defs>
<image width="100%" height="200%" filter="url(#zorrosvg)" xlink:href="data:image/jpeg;base64,${buffer.toString('base64')}"></image>
</svg>`)
});
}
/**
* Generate ZorroSVG luminance masks from PNGs.
* @see https://github.com/Quasimondo/QuasimondoJS/blob/ce7ffb317f7435940046d5ff46a7503f92efd328/zorrosvg/js/zorrosvgmaskmaker.js#L176-L277
* @param {Object} options
*/
module.exports = (options) => {
"use strict";
options = Object.assign({
verbose: process.argv.indexOf('--verbose') !== -1
}, options);
let totalFiles = 0;
return through.obj((file, encoding, callback) => {
if (file.isNull()) {
callback(null, file);
return;
}
if (file.isStream()) {
callback(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
return;
}
if (VALID_EXTS.indexOf(path.extname(file.path).toLowerCase()) === -1) {
if (options.verbose) {
gutil.log(`${PLUGIN_NAME}: Skipping unsupported image ${chalk.blue(file.relative)}`);
}
callback(null, file);
return;
}
/**
* ZorroSVG.
* @note Assumes image has an alpha channel.
* @see https://github.com/Quasimondo/QuasimondoJS/tree/ce7ffb317f7435940046d5ff46a7503f92efd328/zorrosvg
*/
let image = sharp(file.contents);
let errorPrefix = `${chalk.red('✘')} File \`${file.relative}\`: `;
// Create a canvas 2x the height of the original image.
// Keep the original image on top and paste a copy of it on the bottom.
image.toBuffer(function(error, imageBuffer, imageInfo) {
if (error) {
error.message = errorPrefix + error.message;
return callback(new gutil.PluginError(PLUGIN_NAME, error, { showStack: true }));
}
// Force transparent background
return image.background({ r: 0, g: 0, b: 0, alpha: 0 })
// Double canvas height
.extend({ top: 0, right: 0, bottom: imageInfo.height, left: 0 })
// Paste image
.overlayWith(imageBuffer, { top: imageInfo.height, left: 0 })
// Get raw pixel data to manipulate
.raw().toBuffer(function(error, compositeBuffer, compositeInfo) {
if (error) {
error.message = errorPrefix + error.message;
return callback(new gutil.PluginError(PLUGIN_NAME, error, { showStack: true }));
}
// Make the original image fully opaque
for (let i = 0; i < compositeBuffer.length / 2; i = i + 4) {
compositeBuffer[i + 3] = 255;
}
// Create a luminance mask based on the original image's alpha channel
// Add gamma correction for semi-transparent pixels
for (let i = compositeBuffer.length / 2; i < compositeBuffer.length; i = i + 4) {
let alpha = compositeBuffer[i + 3];
compositeBuffer[i + 0] = alpha;
compositeBuffer[i + 1] = alpha;
compositeBuffer[i + 2] = alpha;
compositeBuffer[i + 3] = 255;
}
// Compress as JPG
sharp(compositeBuffer, { raw: { width: compositeInfo.width, height: compositeInfo.height, channels: compositeInfo.channels } })
.jpeg().toBuffer(function(error, finalBuffer, finalInfo) {
if (error) {
error.message = errorPrefix + error.message;
return callback(new gutil.PluginError(PLUGIN_NAME, error, { showStack: true }));
}
// Final SVG conversion
let newFile = getSvg(finalBuffer, {
cwd: file.cwd,
base: file.base,
path: file.path,
width: finalInfo.width,
height: finalInfo.height
});
totalFiles++;
if (options.verbose) {
gutil.log(`${PLUGIN_NAME}: ${chalk.green('✔')} ${chalk.blue(file.relative + ' -> ' + newFile.relative)}`);
}
// TODO: Responsive sizes
callback(null, newFile);
});
});
});
}, callback => {
gutil.log(`${PLUGIN_NAME}: Generated ${totalFiles} ZorroSVG ${plur('file', totalFiles)}.`);
callback();
});
};