abhishek
abhishek

Reputation: 47

Firebase Cloud function imagemagick composite command to overlay images

I am trying to put one image over another image using Imagemagick on cloud function and looked into the Imagemagick command like this:

convert a.png b.png -gravity center -composite result.png

I know it doesnt work like that in firebase cloud function, so I looked for an example and have something like this:

return spawn('convert', [tmpFilePath, tmpFilePath2, '-gravity', 'center', '-composite', tmpFilePath3]);


I get an error like this :

ChildProcessError: convert /tmp/default.jpg /tmp/IMG_4947.JPG -gravity center -composite /tmp/newimage.jpg failed with code 1

Upvotes: 1

Views: 640

Answers (1)

caraie
caraie

Reputation: 1104

I just tried your code and it works.

First import os and path:

const os = require('os');
const path = require('path');

Then you can declare the tmp paths:

const filename1 = 'default.jpg';
const filename2 = 'IMG_4947.JPG';
const filename3 = 'destination.jpg';

const tmpFilePath = path.join(os.tmpdir(), filename1);
const tmpFilePath2 = path.join(os.tmpdir(), filename2);
const tmpFilePath3 = path.join(os.tmpdir(), filename3);

After that you can download the images using your bucket (if you don't have it you can get it from your event).

bucket.file(filename1).download({
            destination: tmpFilePath
        }).then(()=>{
            bucket.file(filename2).download({
                destination: tmpFilePath2
            }).then(()=>{
                return spawn('convert', [tmpFilePath, tmpFilePath2, '-gravity', 'center', '-composite', tmpFilePath3]);
            }).then(()=>{
                //Upload the image (bucket.upload(tmpFilePath3, ....)
            })
        }).catch(()=>{
            //error handling..
        });

It is also possible to do it in parallel instead of sequentially (Promise.all[a, b] instead of then().then()).

Upvotes: 2

Related Questions