forked from kodira/carbone-docker
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimages.js
105 lines (87 loc) · 2.65 KB
/
images.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
const AdmZip = require('adm-zip');
const mimeTypes = require('mime-types');
const sharp = require('sharp');
function imagePath(mimeType, image, index, log) {
let path = image.path;
if (!path) {
const [mime] = mimeType.split(';')
const ext = mimeTypes.extension(mime) || '';
const contentType = mimeTypes.lookup(templatePath);
if (!contentType) {
log.error({templatePath}, 'Unknown content type of the template.')
return;
}
let folder = null;
switch (contentType) {
case 'application/vnd.oasis.opendocument.text':
folder = 'media';
break;
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
folder = 'word/media'
break
default:
log.error('Unsupported content type:' + contentType)
return;
}
path = folder + '/image' + (index + 1) + '.' + ext;
} else if (path.startsWith('/')) {
path = path.substring(1);
}
return path;
}
const defaultResizeOptions = {
fit: 'contain',
background: {r: 255, g: 255, b: 255, alpha: 1},
};
async function scaleImage(originalImage, newImage, resize) {
const originalMetadata = await sharp(originalImage).metadata();
if (resize === false) {
return newImage;
}
const options = typeof resize === 'object' ? {...defaultResizeOptions, ...resize} : defaultResizeOptions;
return await sharp(newImage)
.resize(
originalMetadata.width,
originalMetadata.height,
options)
.toBuffer();
}
async function replaceImages(images, templatePath, log) {
if (!Array.isArray(images)) {
throw new Error('Images must be an array.')
}
if (images.length === 0) {
return;
}
let zip = new AdmZip(templatePath);
images = images
.filter(image => typeof image.content === 'string' && image.content.startsWith('data:'))
// Async loop
for (let index = 0; index < images.length; index += 1) {
const image = images[index];
const [mimeType, data] = image.content.substring(5).split(',');
if (!mimeType || !data) {
log.info('Image will not be added. Wrong format.')
continue
}
const path = imagePath(mimeType, image, index, log);
const entry = zip.getEntry(path);
if (!entry) {
log.error('Image in the path ' + path + ' does not exists.')
continue
}
try {
const originalImage = entry.getData();
const newImage = Buffer.from(data, 'base64');
const scaledImage = await scaleImage(originalImage, newImage, image.resize);
zip.addFile(path, scaledImage);
log.info({path}, 'Image replaced.');
} catch (e) {
log.error(e);
}
}
zip.writeZip();
}
module.exports = {
replaceImages
}