summaryrefslogtreecommitdiff
path: root/src/services/drive/image-processor.ts
blob: 4b8db0e0c86c4ff98cb65e04c371a40f36dd2007 (plain)
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
import * as sharp from 'sharp';
import * as fs from 'fs';

export type IImage = {
	data: Buffer;
	ext: string | null;
	type: string;
};

/**
 * Convert to JPEG
 *   with resize, remove metadata, resolve orientation, stop animation
 */
export async function convertToJpeg(path: string, width: number, height: number): Promise<IImage> {
	const data = await sharp(path)
		.resize(width, height, {
			fit: 'inside',
			withoutEnlargement: true
		})
		.rotate()
		.jpeg({
			quality: 85,
			progressive: true
		})
		.toBuffer();

	return {
		data,
		ext: 'jpg',
		type: 'image/jpeg'
	};
}

/**
 * Convert to WebP
 *   with resize, remove metadata, resolve orientation, stop animation
 */
export async function convertToWebp(path: string, width: number, height: number): Promise<IImage> {
	const data = await sharp(path)
		.resize(width, height, {
			fit: 'inside',
			withoutEnlargement: true
		})
		.rotate()
		.webp({
			quality: 85
		})
		.toBuffer();

	return {
		data,
		ext: 'webp',
		type: 'image/webp'
	};
}

/**
 * Convert to PNG
 *   with resize, remove metadata, resolve orientation, stop animation
 */
export async function convertToPng(path: string, width: number, height: number): Promise<IImage> {
	const data = await sharp(path)
		.resize(width, height, {
			fit: 'inside',
			withoutEnlargement: true
		})
		.rotate()
		.png()
		.toBuffer();

	return {
		data,
		ext: 'png',
		type: 'image/png'
	};
}

/**
 * Convert to GIF (Actually just NOP)
 */
export async function convertToGif(path: string): Promise<IImage> {
	const data = await fs.promises.readFile(path);

	return {
		data,
		ext: 'gif',
		type: 'image/gif'
	};
}

/**
 * Convert to APNG (Actually just NOP)
 */
export async function convertToApng(path: string): Promise<IImage> {
	const data = await fs.promises.readFile(path);

	return {
		data,
		ext: 'apng',
		type: 'image/apng'
	};
}