node.jsamazon-web-servicesamazon-s3aws-lambdajimp

image cannot able to read using jimp from s3 bucket & lambda


I'm using jimp plugin to read file & trying to optimize images. I can able to read file & optimize using public image url's.

The issue is while reading image from s3 bucket. I can able to fetch image from s3 bucket, while passing the image to jimp.read(buffer) as buffer it's not working and not able to get any error as well.

Here my code:

module.exports.handler = async (event, context, callback) => {

// Get the object from the event and show its content type
const bucket = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));

const params = {
    Bucket: bucket,
    Key: key,
};
console.log("params ::::::::::", params);
try {
    let objectId = uuidv4();
    let objectKey = `resize-${width}x${height}-${objectId}.jpg`;

    const origimage = await s3.getObject(params).promise();
    console.log("origimage ====>", origimage.Body);
    Jimp.read(origimage.Body)
    .then(image => image.resize(width, height)
        .getBufferAsync(imageType))
    .then(resizedBuffer => uploadToS3(resizedBuffer, objectKey))
    .then(function(response) {
        console.log(`Image ${objectKey} was uploaed and resized`);
        callback(null, {
            statusCode: 200, 
            body: JSON.stringify(response)
        });
    })
    .catch(error => console.log(error));
    

} catch (err) {
    console.log(err);
    const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
    console.log(message);
    throw new Error(message);
}

here is the response which i got from s3 bucket:

  2022-10-13T09:19:25.099Z  924b89b2-69ab-467e-8143-6f9e22e5e67a    INFO    CONTENT DATA: {
  AcceptRanges: 'bytes',
  LastModified: 2022-10-12T11:58:38.000Z,
  ContentLength: 331338,
  ETag: '"917eba20c634253a97ff6dfe3958db0a"',
  ContentType: 'image/jpeg',
  Metadata: {},
  Body: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 43 00 03 02 02 02 02 02 03 02 02 02 03 03 03 03 04 06 04 04 04 04 04 08 06 06 05 ... 331288 more bytes>
}

Is there anything that i'm missing while sending buffer data to jimp.read function. I have tried passing imagename & base64 as well, still no luck.

Is there anyway i can access s3 bucket image using image url with in lambda fuction?

Thanks in advance


Solution

  • It doesn't look like you're waiting for the promise that Jimp.read(buffer) creates to resolve/reject.

    Try await Jimp.read(...) and you should get something back in the way of the promise resolving/rejecting, triggering some of your logging.

    Equally, you could also do return Jimp.read(...) and Lambda will wait for that promise to complete before ending execution.