@@ -5,54 +5,62 @@ import type { MetadataConfig } from '../core-config'
5
5
const getQuality = ( size : number ) => Math . round ( 92.647 - 1.683e-6 * size )
6
6
const CompressedData = Symbol ( 'CompressedData' )
7
7
8
- let imagePool : ImagePoolType
8
+ let imagePool : Promise < ImagePoolType >
9
9
const initImagePool = async ( ) => {
10
10
if ( imagePool ) {
11
11
return
12
12
}
13
- const { ImagePool } = await import ( '@squoosh/lib' )
14
- imagePool = new ImagePool ( cpus ( ) . length )
13
+ imagePool = ( async ( ) => {
14
+ const { ImagePool } = await import ( '@squoosh/lib' )
15
+ return new ImagePool ( cpus ( ) . length )
16
+ } ) ( )
15
17
}
16
18
17
19
export type CompressedBuffer = Buffer & {
18
- [ CompressedData ] : Buffer
20
+ [ CompressedData ] : Promise < Buffer >
19
21
}
20
22
export const compressImage = async ( buffer : Buffer | CompressedBuffer , resolution ?: number ) => {
21
23
await initImagePool ( )
22
- if ( buffer [ CompressedData ] ) {
23
- return buffer [ CompressedData ] as Buffer
24
- }
25
- const { default : imageInfo } = await import ( 'imageinfo' )
26
- const info = imageInfo ( buffer )
27
- const resize = ( ( ) => {
28
- if ( ! resolution ) {
29
- return undefined
30
- }
31
- if ( info . width > resolution ) {
32
- return {
33
- width : resolution ,
34
- }
35
- }
36
- if ( info . height > resolution ) {
37
- return {
38
- height : resolution ,
39
- }
40
- }
41
- return undefined
42
- } ) ( )
43
- const image = imagePool . ingestImage ( buffer )
24
+ if ( ! buffer [ CompressedData ] ) {
25
+ buffer [ CompressedData ] = ( async ( ) => {
26
+ const { default : imageInfo } = await import ( 'imageinfo' )
27
+ const info = imageInfo ( buffer )
28
+ const resize = ( ( ) => {
29
+ if ( ! resolution ) {
30
+ return undefined
31
+ }
32
+ if ( info . width > resolution ) {
33
+ return {
34
+ width : resolution ,
35
+ }
36
+ }
37
+ if ( info . height > resolution ) {
38
+ return {
39
+ height : resolution ,
40
+ }
41
+ }
42
+ return undefined
43
+ } ) ( )
44
+ const pool = await imagePool
45
+ const image = pool . ingestImage ( buffer )
44
46
45
- await image . preprocess ( {
46
- resize,
47
- } )
48
- const result = await image . encode ( {
49
- mozjpeg : {
50
- quality : getQuality ( buffer . length ) ,
51
- } ,
52
- } )
53
- const resultBuffer = Buffer . from ( result . mozjpeg . binary ) as CompressedBuffer
54
- buffer [ CompressedData ] = resultBuffer
55
- return resultBuffer
47
+ await image . preprocess (
48
+ resize
49
+ ? {
50
+ resize,
51
+ }
52
+ : undefined ,
53
+ )
54
+ const result = await image . encode ( {
55
+ mozjpeg : {
56
+ quality : getQuality ( buffer . length ) ,
57
+ } ,
58
+ } )
59
+ const resultBuffer = Buffer . from ( result . mozjpeg . binary ) as CompressedBuffer
60
+ return resultBuffer
61
+ } ) ( )
62
+ }
63
+ return ( buffer as CompressedBuffer ) [ CompressedData ]
56
64
}
57
65
export const compressImageByConfig = async (
58
66
buffer : Buffer | CompressedBuffer ,
0 commit comments