Closed soun997 closed 3 weeks ago
import { S3Client, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3"; import sharp from 'sharp'; const s3 = new S3Client({ region: 'ap-northeast-2' }); export async function handler(event) { // S3 버킷과 객체 키 가져오기 const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const quality = 80; try { // S3에서 이미지 가져오기 const getObjectCmd = new GetObjectCommand({ Bucket: bucket, Key: key }); const s3Object = await s3.send(getObjectCmd); const image = await s3Object.Body.transformToByteArray(); // 새 키 생성 (확장자를 .webp로 변경) const newKey = key.replace(/\.[^/.]+$/, ".webp"); // 이미지를 WebP로 변환 const webpBuffer = await sharp(image) .withMetadata() .toFormat('webp', { quality: quality, lossless: false }) .toFile(newKey, (err, info) => console.log) .toBuffer(); // 변환된 이미지를 S3에 업로드 const putObjectCmd = new PutObjectCommand({ Bucket: bucket, Key: newKey, Body: webpBuffer, ContentType: 'image/webp' }); await s3.send(putObjectCmd); console.log(`Successfully compressed and uploaded: ${newKey}`); return { statusCode: 200, body: JSON.stringify('Image processed successfully') }; } catch (error) { console.error('Error processing image:', error); return { statusCode: 500, body: JSON.stringify('Error processing image') }; } }
이슈 번호 (#317)
요약
문제
아이디어
해결
Node.js 기반 이미지 압축 로직 코드