-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathpath.ts
60 lines (57 loc) · 1.64 KB
/
path.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
import {
isUrl,
getImageSize,
getFSFile,
getURLFile
} from '../../utils/common'
import { IPicGo, IPathTransformedImgInfo, IImgInfo, IImgSize } from '../../types'
import dayjs from 'dayjs'
const handle = async (ctx: IPicGo): Promise<IPicGo> => {
const results: IImgInfo[] = ctx.output
await Promise.all(ctx.input.map(async (item: string | Buffer, index: number) => {
let info: IPathTransformedImgInfo
if (Buffer.isBuffer(item)) {
info = {
success: true,
buffer: item,
fileName: '', // will use getImageSize result
extname: '' // will use getImageSize result
}
} else if (isUrl(item)) {
info = await getURLFile(item, ctx)
} else {
info = await getFSFile(item)
}
if (info.success && info.buffer) {
const imgSize = getImgSize(ctx, info.buffer, item)
const extname = info.extname || imgSize.extname || '.png'
results[index] = {
buffer: info.buffer,
fileName: info.fileName || `${dayjs().format('YYYYMMDDHHmmssSSS')}${extname}}`,
width: imgSize.width,
height: imgSize.height,
extname
}
} else {
ctx.log.error(info.reason)
}
}))
// remove empty item
ctx.output = results.filter(item => item)
return ctx
}
const getImgSize = (ctx: IPicGo, file: Buffer, path: string | Buffer): IImgSize => {
const imageSize = getImageSize(file)
if (!imageSize.real) {
if (typeof path === 'string') {
ctx.log.warn(`can't get ${path}'s image size`)
} else {
ctx.log.warn('can\'t get image size')
}
ctx.log.warn('fallback to 200 * 200')
}
return imageSize
}
export default {
handle
}