Skip to content

Commit

Permalink
feat(): forced-compression
Browse files Browse the repository at this point in the history
  • Loading branch information
AlenVelocity committed Feb 23, 2024
1 parent 141e979 commit 244ef55
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
9 changes: 8 additions & 1 deletion src/Types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ export interface IStickerConfig {
}

export interface IStickerOptions extends IStickerConfig {
/** How you want your sticker to look like
/**
* How you want your sticker to look like
* Can be crop or full. Defaults to 'default' (no changes)
*/
type?: StickerTypes | string
Expand All @@ -27,6 +28,12 @@ export interface IStickerOptions extends IStickerConfig {
* Background Color of the sticker (only for type full)
*/
background?: Color
/**
* Force webp compression. Defaults to false
* If true, it will compress the sticker to under 1MB
* Ignored if quality is set
*/
forceCompression?: boolean
}

export interface IRawMetadata {
Expand Down
Empty file added src/internal/compress.ts
Empty file.
12 changes: 11 additions & 1 deletion src/internal/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { IStickerOptions } from '..'
const convert = async (
data: Buffer,
mime: string,
{ quality = 100, background = defaultBg, type = StickerTypes.DEFAULT }: IStickerOptions
{ quality = 101, background = defaultBg, type = StickerTypes.DEFAULT, forceCompression = false }: IStickerOptions
): Promise<Buffer> => {
const isVideo = mime.startsWith('video')
let image = isVideo ? await videoToGif(data) : data
Expand Down Expand Up @@ -76,6 +76,16 @@ const convert = async (
break
}

if (forceCompression && quality > 100) {
quality = 100
let compressed = await img.toBuffer()
while (compressed.length > 1024 * 1024 && quality > 0) {
quality == 5 ? (quality = 1) : (quality -= 5)
compressed = await img.webp({ quality: quality }).toBuffer()
}
return compressed
} else if (quality > 100) quality = 100

return await img
.webp({
quality,
Expand Down

0 comments on commit 244ef55

Please sign in to comment.