feat: bluesky resize image
This commit is contained in:
parent
92b8feb093
commit
30c7ae7dc5
|
|
@ -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)])
|
||||
);
|
||||
}) || []
|
||||
);
|
||||
|
|
|
|||
Loading…
Reference in New Issue