Skip to content

Commit

Permalink
Fix resize params
Browse files Browse the repository at this point in the history
  • Loading branch information
the1812 committed Sep 3, 2023
1 parent 8cc22fa commit 26045c2
Showing 1 changed file with 45 additions and 37 deletions.
82 changes: 45 additions & 37 deletions src/core/writer/image-compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,62 @@ import type { MetadataConfig } from '../core-config'
const getQuality = (size: number) => Math.round(92.647 - 1.683e-6 * size)
const CompressedData = Symbol('CompressedData')

let imagePool: ImagePoolType
let imagePool: Promise<ImagePoolType>
const initImagePool = async () => {
if (imagePool) {
return
}
const { ImagePool } = await import('@squoosh/lib')
imagePool = new ImagePool(cpus().length)
imagePool = (async () => {
const { ImagePool } = await import('@squoosh/lib')
return new ImagePool(cpus().length)
})()
}

export type CompressedBuffer = Buffer & {
[CompressedData]: Buffer
[CompressedData]: Promise<Buffer>
}
export const compressImage = async (buffer: Buffer | CompressedBuffer, resolution?: number) => {
await initImagePool()
if (buffer[CompressedData]) {
return buffer[CompressedData] as Buffer
}
const { default: imageInfo } = await import('imageinfo')
const info = imageInfo(buffer)
const resize = (() => {
if (!resolution) {
return undefined
}
if (info.width > resolution) {
return {
width: resolution,
}
}
if (info.height > resolution) {
return {
height: resolution,
}
}
return undefined
})()
const image = imagePool.ingestImage(buffer)
if (!buffer[CompressedData]) {
buffer[CompressedData] = (async () => {
const { default: imageInfo } = await import('imageinfo')
const info = imageInfo(buffer)
const resize = (() => {
if (!resolution) {
return undefined
}
if (info.width > resolution) {
return {
width: resolution,
}
}
if (info.height > resolution) {
return {
height: resolution,
}
}
return undefined
})()
const pool = await imagePool
const image = pool.ingestImage(buffer)

await image.preprocess({
resize,
})
const result = await image.encode({
mozjpeg: {
quality: getQuality(buffer.length),
},
})
const resultBuffer = Buffer.from(result.mozjpeg.binary) as CompressedBuffer
buffer[CompressedData] = resultBuffer
return resultBuffer
await image.preprocess(
resize
? {
resize,
}
: undefined,
)
const result = await image.encode({
mozjpeg: {
quality: getQuality(buffer.length),
},
})
const resultBuffer = Buffer.from(result.mozjpeg.binary) as CompressedBuffer
return resultBuffer
})()
}
return (buffer as CompressedBuffer)[CompressedData]
}
export const compressImageByConfig = async (
buffer: Buffer | CompressedBuffer,
Expand Down

0 comments on commit 26045c2

Please sign in to comment.