This repository has been archived by the owner on Jul 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.ts
63 lines (53 loc) · 2.03 KB
/
image.ts
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
import * as fs from 'fs';
import * as util from 'util';
import { CommandService, spawn } from '@travetto/exec';
import { Cacheable } from '@travetto/cache';
import { Injectable } from '@travetto/di';
import { CommonProcess, ExecutionResult } from '@travetto/exec/src/types';
import { AppEnv } from '@travetto/base';
import { AssetService } from './asset';
import { Asset, AssetMetadata } from '../model';
import { AssetUtil } from '../util';
const fsUnlinkAsync = util.promisify(fs.unlink);
const fsWriteFile = util.promisify(fs.writeFile);
@Injectable()
export class ImageService {
converter = new CommandService({
image: 'v4tech/imagemagick',
checkForLocal: async () => {
return (await spawn('convert --version')[1]).valid;
}
});
constructor(private assetService: AssetService) { }
@Cacheable({
max: 1000,
dispose: (key: string, n: Promise<string | undefined>) => {
n.then(v => v ? fsUnlinkAsync(v) : undefined).catch(err => {
console.error(err);
});
}
})
async generateAndStoreImage(filename: string, options: { w: number, h: number }, hasTags?: string[]): Promise<string | undefined> {
const info = await this.assetService.get(filename, hasTags);
if (!info.stream) {
throw new Error('Stream not found');
}
if (options && (options.w || options.h)) {
const filePath = AssetUtil.generateTempFile(info.filename.split('.').pop() as string);
const [proc, prom] = await this.converter.exec('convert', '-resize', `${options.w}x${options.h}`, '-auto-orient', '-', '-');
info.stream.pipe(proc.stdin);
proc.stdout.pipe(fs.createWriteStream(filePath));
await prom;
return filePath;
}
}
async getImage(filename: string, options: { w: number, h: number }, hasTags?: string[]): Promise<Asset> {
const file = await this.generateAndStoreImage(filename, options, hasTags);
const info = await this.assetService.get(filename, hasTags);
if (file) {
info.stream = fs.createReadStream(file);
delete info.length;
}
return info;
}
}