-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
image.js
39 lines (35 loc) · 899 Bytes
/
image.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
/*
PDFImage - embeds images in PDF documents
By Devon Govett
*/
import fs from 'fs';
import JPEG from './image/jpeg';
import PNG from './image/png';
class PDFImage {
static open(src, label) {
let data;
if (Buffer.isBuffer(src)) {
data = src;
} else if (src instanceof ArrayBuffer) {
data = Buffer.from(new Uint8Array(src));
} else {
let match;
if ((match = /^data:.+?;base64,(.*)$/.exec(src))) {
data = Buffer.from(match[1], 'base64');
} else {
data = fs.readFileSync(src);
if (!data) {
return;
}
}
}
if (data[0] === 0xff && data[1] === 0xd8) {
return new JPEG(data, label);
} else if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') {
return new PNG(data, label);
} else {
throw new Error('Unknown image format.');
}
}
}
export default PDFImage;