From 244ef5535227cf135bcf24099046cbd28b879a3d Mon Sep 17 00:00:00 2001 From: AlenVelocity Date: Fri, 23 Feb 2024 19:50:27 +0530 Subject: [PATCH] feat(): forced-compression --- src/Types.ts | 9 ++++++++- src/internal/compress.ts | 0 src/internal/convert.ts | 12 +++++++++++- 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 src/internal/compress.ts diff --git a/src/Types.ts b/src/Types.ts index f07d1a0..0eb04e2 100644 --- a/src/Types.ts +++ b/src/Types.ts @@ -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 @@ -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 { diff --git a/src/internal/compress.ts b/src/internal/compress.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/internal/convert.ts b/src/internal/convert.ts index e66c413..ce22d55 100644 --- a/src/internal/convert.ts +++ b/src/internal/convert.ts @@ -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 => { const isVideo = mime.startsWith('video') let image = isVideo ? await videoToGif(data) : data @@ -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,