2019-02-04 19:01:36 +01:00
|
|
|
import * as sharp from 'sharp';
|
2019-05-15 14:27:20 +02:00
|
|
|
import * as fs from 'fs';
|
2019-02-04 19:01:36 +01:00
|
|
|
|
|
|
|
export type IImage = {
|
|
|
|
data: Buffer;
|
2019-04-12 18:43:22 +02:00
|
|
|
ext: string | null;
|
2019-02-04 19:01:36 +01:00
|
|
|
type: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert to JPEG
|
|
|
|
* with resize, remove metadata, resolve orientation, stop animation
|
|
|
|
*/
|
2019-05-15 14:27:20 +02:00
|
|
|
export async function convertToJpeg(path: string, width: number, height: number): Promise<IImage> {
|
2019-02-04 19:01:36 +01:00
|
|
|
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
|
|
|
|
*/
|
2019-05-15 14:27:20 +02:00
|
|
|
export async function convertToWebp(path: string, width: number, height: number): Promise<IImage> {
|
2019-02-04 19:01:36 +01:00
|
|
|
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
|
|
|
|
*/
|
2019-05-15 14:27:20 +02:00
|
|
|
export async function convertToPng(path: string, width: number, height: number): Promise<IImage> {
|
2019-02-04 19:01:36 +01:00
|
|
|
const data = await sharp(path)
|
|
|
|
.resize(width, height, {
|
|
|
|
fit: 'inside',
|
|
|
|
withoutEnlargement: true
|
|
|
|
})
|
|
|
|
.rotate()
|
|
|
|
.png()
|
|
|
|
.toBuffer();
|
|
|
|
|
|
|
|
return {
|
|
|
|
data,
|
|
|
|
ext: 'png',
|
|
|
|
type: 'image/png'
|
|
|
|
};
|
|
|
|
}
|
2019-05-15 14:27:20 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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',
|
2019-07-03 16:43:09 +02:00
|
|
|
type: 'image/vnd.mozilla.apng'
|
2019-05-15 14:27:20 +02:00
|
|
|
};
|
|
|
|
}
|