Converting JPG to WebP in AWS Lambda using GraphicsMagick / ImageMagick packages in Node.js

I am using AWS Lambda example script to resize JPG image using Node.js and ImageMagick / GraphicsMagick libraries. I want to do a simple modification to convert an image from JPG to WebP format after resizing. (GraphicsMagick doesn't support WebP, but ImageMagick does, which is subclassed in the script). This should be possible with the following block of code as in the example in the Buffers section here (which converts JPG to PNG).

gm('img.jpg')
.resize(100, 100)
.toBuffer('PNG',function (err, buffer) {
  if (err) return handle(err);
  console.log('done!');
})

      

When I run this block of code on a local Node.js installation (replacing PNG with WebP) it works.

When I modify the transform function (see below) the AWS Lambda example script , however, and execute it on AWS, I get the following "Stream gives an empty buffer" :

Unable to resize mybucket/104A0378.jpg and upload to mybucket_resized/resized-104A0378.jpg due to an error: Error: Stream yields empty buffer

      

Modified transform () function (see the line with "webp"):

function tranform(response, next) {
            gm(response.Body).size(function(err, size) {
                // Infer the scaling factor to avoid stretching the image unnaturally.
                var scalingFactor = Math.min(
                    MAX_WIDTH / size.width,
                    MAX_HEIGHT / size.height
                );
                var width  = scalingFactor * size.width;
                var height = scalingFactor * size.height;

                // Transform the image buffer in memory.
                this.resize(width, height)
                    .toBuffer('webp', function(err, buffer) {
                        if (err) {
                            next(err);
                        } else {
                            next(null, response.ContentType, buffer);
                        }
                    });
            });
        }

      

I understand that response.ContentType is still image / jpeg, but I don't think it plays a role here. Also, I understand that I should probably convert to WebP before resizing, but ... baby steps!

Any ideas?

+3


source to share


2 answers


ImageMagick must be specially compiled with WebP support. My experiments seem to show that ImageMagick on AWS Lambda is not compiled with WEBP :(



+1


source


I ran into the same error, "Stream gives an empty buffer", in other operations using gm and AWS lambda.

It turns out that the lambda container is out of memory.

I tested this assumption using a large image that kept throwing an error.



When I increased the memory of the lambda function everything worked fine.

Hope this helps you too.

+2


source







All Articles