Image response using Imagemagick

Hi, I’m using imagemagick to resize and crop images,
I want to return the cropped image back to the client using the http request.

In a regular express app I would just do res.end(stdout, 'binary');
Where stdout is the binary result from imagemagick .resize method.

However, trying to return it using serverless does not seem to work.
How am I suppose to return the image back to the clients?

Thanks,
Matan

Can this help? https://github.com/maciejtreder/serverless-apigw-binary

I’m not actually sure though, because it seems like that plugin is to deal with binary payloads (incoming requests), whereas you are talking about responding with a binary body.

In a serverless environment, you can return the image to the client by encoding it as base64 and setting the appropriate content type in the HTTP response. Here’s an example of how to do this in Node.js using the AWS Lambda framework:

const { spawn } = require('child_process');
const AWS = require('aws-sdk');

exports.handler = async (event) => {
    const s3 = new AWS.S3();
    const bucketName = 'your-bucket-name';
    const key = 'your-image-key.jpg';

    const convert = spawn('convert', ['input.jpg', '-resize', '100x100', 'output.jpg']);

    convert.stdout.on('data', (data) => {
        // Handle the image data from ImageMagick
        const imageData = data.toString('base64');

        // Set the HTTP response
        const response = {
            statusCode: 200,
            isBase64Encoded: true,
            headers: {
                'Content-Type': 'image/jpeg',
            },
            body: imageData,
        };

        return response;
    });

    convert.stderr.on('data', (data) => {
        console.error(`Error: ${data}`);
    });

    convert.on('close', (code) => {
        console.log(`ImageMagick process exited with code ${code}`);
    });
};

This code uses AWS Lambda and S3 to store and retrieve the image. You would need to adapt it to your specific serverless uncomfortable cursed images environment and storage solution. Remember to replace 'your-bucket-name' and 'your-image-key.jpg' with your actual S3 bucket name and image key.