generated from actions/typescript-action
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathimage.ts
82 lines (61 loc) · 1.86 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import {debug, info} from '@actions/core'
import {statSync} from 'fs'
import tinify from 'tinify'
import bytes from 'bytes'
import {imageSize} from 'image-size'
import {promisify} from 'util'
import {
getCompressionSummary,
getResizeOptions,
isResizable
} from './image-utils'
import Exif, {Tag} from './exif'
const sizeOf = promisify(imageSize)
/** Software Exif value used to maintain state */
const SOFTWARE_TAG = 'tinify.com'
export interface Compress {
resizeWidth?: number
resizeHeight?: number
}
export default class Image {
private readonly exif: Exif
private readonly sizes: number[] = []
constructor(private readonly filename: string) {
this.exif = new Exif(filename)
}
async compress(compress: Compress = {}): Promise<boolean> {
info(`[${this.filename}] Checking Exif state`)
if (SOFTWARE_TAG === (await this.exif.get([Tag.Software])).trim()) {
info(`[${this.filename}] Skipping already compressed image`)
return false
}
this.setSize()
info(`[${this.filename}] Compressing image`)
let source = tinify.fromFile(this.filename)
debug(`[${this.filename}] Retrieving image size`)
const dimensions = await sizeOf(this.filename)
if (isResizable(compress, dimensions)) {
info(`[${this.filename}] Resizing image`)
source = source.resize(getResizeOptions(compress))
}
await source.toFile(this.filename)
info(`[${this.filename}] Setting Exif state`)
await this.exif.set([
[Tag.Software, SOFTWARE_TAG],
[Tag.XMPToolkit, '']
])
this.setSize()
return true
}
getFilename(): string {
return this.filename
}
getCompressionSummary(): string {
return getCompressionSummary(this.sizes)
}
private setSize(): void {
const size = statSync(this.filename).size
this.sizes.push(size)
debug(`[${this.filename}] ${bytes.format(size)}`)
}
}