Created
November 25, 2024 05:56
-
-
Save SahilMahadwar/a547aeeba3f8c804bf0c0c7c65a185e6 to your computer and use it in GitHub Desktop.
Lambda image resizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWS = require('aws-sdk'); | |
const sharp = require('sharp'); | |
const s3 = new AWS.S3(); | |
exports.handler = async (event) => { | |
try { | |
const bucket = event.Records[0].s3.bucket.name; | |
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); | |
const outputKey = `resized/${key}`; | |
const resizeWidth = 800; // Width to resize the image to | |
// Fetch the original image from S3 | |
const originalImage = await s3.getObject({ | |
Bucket: bucket, | |
Key: key | |
}).promise(); | |
// Resize the image using sharp | |
const resizedImage = await sharp(originalImage.Body) | |
.resize({ width: resizeWidth }) | |
.toBuffer(); | |
// Save the resized image back to S3 | |
await s3.putObject({ | |
Bucket: bucket, | |
Key: outputKey, | |
Body: resizedImage, | |
ContentType: 'image/jpeg' // Update based on your file type | |
}).promise(); | |
console.log(`Image resized and uploaded to ${outputKey}`); | |
return { | |
statusCode: 200, | |
body: JSON.stringify({ | |
message: 'Image resized successfully', | |
resizedKey: outputKey | |
}) | |
}; | |
} catch (error) { | |
console.error('Error processing image:', error); | |
return { | |
statusCode: 500, | |
body: JSON.stringify({ | |
message: 'Error resizing image', | |
error: error.message | |
}) | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment