Skip to content

Commit

Permalink
feat: bluesky resize image
Browse files Browse the repository at this point in the history
  • Loading branch information
nevo-david committed Jan 3, 2025
1 parent 92b8feb commit 30c7ae7
Showing 1 changed file with 35 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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)])
);
}) || []
);
Expand Down

0 comments on commit 30c7ae7

Please sign in to comment.