lovell / sharp

High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.
https://sharp.pixelplumbing.com
Apache License 2.0
29.33k stars 1.3k forks source link

Input buffer contains unsupported image format inside Lambda function #4224

Closed solomonmulatu closed 1 month ago

solomonmulatu commented 1 month ago

I am experiencing an issue with the sharp library when used inside an AWS Lambda function. The error message received is: "Input buffer contains unsupported image format".

Steps to Reproduce Set up an AWS Lambda function to handle image uploads via multipart/form-data. Use API Gateway to forward binary data to Lambda with base64 encoding. Decode the base64 string in the Lambda function. Pass the buffer to sharp to resize and upload the image. Here is a snippet of the Lambda function that parses the image and uses sharp:

`const sharp = require('sharp'); const buffer = Buffer.from(imageData, 'base64');

sharp(buffer) .resize(200, 200) .toFormat('jpeg') .toBuffer() .then((data) => { // process data... }) .catch((err) => { console.error("Error: ", err.message); }); ` Expected Behavior The image should be resized and processed without any issues.

Actual Behavior The function throws the following error: Input buffer contains unsupported image format

Additional Context Sharp version: 0.32.6 Environment: AWS Lambda Operating System: Lambda AMI (Amazon Linux 2) The issue only happens when the input is a multipart form upload. The same code works perfectly when the image is sent as a base64 string.

I have already ensured that:

Binary media types are enabled in API Gateway. API Gateway is forwarding the image as a binary. Sharp works with the same input locally but fails in the Lambda environment. Possible Workaround The issue does not occur when the image is uploaded as base64 directly. However, this workaround is not ideal since I need to support multipart/form-data uploads.

Any help or guidance would be appreciated

lovell commented 1 month ago

This is almost certainly a misconfiguration in API Gateway unrelated to sharp.

https://sharp.pixelplumbing.com/install#aws-lambda https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html

solomonmulatu commented 1 month ago

i found the solution and this was the fix Globals: Api: BinaryMediaTypes: ['~1']