Completed
Push — master ( 57140e...ff6124 )
by Jan
14s queued 12s
created

src/frames/util-picture.ts   A

Complexity

Total Complexity 8
Complexity/F 4

Size

Lines of Code 37
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 29
mnd 6
bc 6
fnc 2
dl 0
loc 37
rs 10
bpm 3
cpm 4
noi 0
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A util-picture.ts ➔ getPictureMimeTypeFromBuffer 0 15 3
A util-picture.ts ➔ retrievePictureAndMimeType 0 17 5
1
import * as fs from "fs"
2
import { isBuffer } from "../util"
3
4
function getPictureMimeTypeFromBuffer(pictureBuffer: Buffer) {
5
    if (
6
        pictureBuffer.length > 3 &&
7
        pictureBuffer.compare(Buffer.from([0xff, 0xd8, 0xff]), 0, 3, 0, 3) === 0
8
    ) {
9
        return "image/jpeg"
10
    }
11
    if (
12
        pictureBuffer.length > 8 &&
13
        pictureBuffer.compare(Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]), 0, 8, 0, 8) === 0
14
    ) {
15
        return "image/png"
16
    }
17
    return ""
18
}
19
20
export function retrievePictureAndMimeType({
21
    filenameOrBuffer,
22
    mimeType
23
}: {
24
    filenameOrBuffer?: Buffer | string
25
    mimeType?: string
26
}) {
27
    if (!filenameOrBuffer) {
28
        throw new TypeError("Missing image buffer or filename")
29
    }
30
    const pictureBuffer = isBuffer(filenameOrBuffer) ?
31
        filenameOrBuffer : fs.readFileSync(filenameOrBuffer)
32
    return {
33
        pictureBuffer,
34
        mimeType: mimeType ?? getPictureMimeTypeFromBuffer(pictureBuffer)
35
    }
36
}
37