From 30c7ae7dc5163bd7a1826c7632640420a84e47c7 Mon Sep 17 00:00:00 2001 From: Nevo David Date: Fri, 3 Jan 2025 23:49:27 +0700 Subject: [PATCH] feat: bluesky resize image --- .../integrations/social/bluesky.provider.ts | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts b/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts index 042382368..361949101 100644 --- a/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts +++ b/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts @@ -16,6 +16,40 @@ import { AuthService } from '@gitroom/helpers/auth/auth.service'; import sharp from 'sharp'; import { Plug } from '@gitroom/helpers/decorators/plug.decorator'; import { timer } from '@gitroom/helpers/utils/timer'; +import axios from 'axios'; + +async function reduceImageBySize(url: string, maxSizeKB = 976) { + try { + // Fetch the image from the URL + const response = await axios.get(url, { responseType: 'arraybuffer' }); + let imageBuffer = Buffer.from(response.data); + + // Use sharp to get the metadata of the image + const metadata = await sharp(imageBuffer).metadata(); + let width = metadata.width!; + let height = metadata.height!; + + // Resize iteratively until the size is below the threshold + while (imageBuffer.length / 1024 > maxSizeKB) { + width = Math.floor(width * 0.9); // Reduce dimensions by 10% + height = Math.floor(height * 0.9); + + // Resize the image + const resizedBuffer = await sharp(imageBuffer) + .resize({ width, height }) + .toBuffer(); + + imageBuffer = resizedBuffer; + + if (width < 10 || height < 10) break; // Prevent overly small dimensions + } + + return imageBuffer; + } catch (error) { + console.error('Error processing image:', error); + throw error; + } +} export class BlueskyProvider extends SocialAbstract implements SocialProvider { identifier = 'bluesky'; @@ -130,7 +164,7 @@ export class BlueskyProvider extends SocialAbstract implements SocialProvider { const images = await Promise.all( post.media?.map(async (p) => { return await agent.uploadBlob( - new Blob([await (await fetch(p.url)).arrayBuffer()]) + new Blob([await reduceImageBySize(p.url)]) ); }) || [] );