1

I'm trying to compose two images on top of each other using the Node.js gm library. For the final image, avatar.png needs to go on top of bg.png. Here's the code I started with:

const image = gm("bg.png")
    .composite("avatar.png");

This works the way it should, but I also needed to move the image over to an x, y of 50, 50, so I used the geometry() function:

const image = gm("bg.png")
    .composite("avatar.png")
    .geometry("+50+50");

The next problem is that I needed to scale the image up to be 200x200, so I tried a few things to do this:

const image = gm("bg.png")
    .composite("avatar.png")
    .geometry("200x200+50+50");

This ended up scaling bg.png to be as close to 200x200 as possible while still preserving the aspect ratio of the image. Since that didn't work, I tried this:

const image = gm("bg.png")
    .composite("avatar.png")
    .resize("200x200")
    .geometry("+50+50");

This just ignored the resize() function and didn't scale anything at all. Swapping the order of resize() and geometry() also didn't do anything.

How can I scale avatar.png to be 200x200?

APixel Visuals
  • 1,508
  • 4
  • 20
  • 38

2 Answers2

0

Looks like any function that gets called only applies to the image passed in the constructor even after calling composite.

You have do the processing separately:

gm("bg.png")
  .geometry("+50+50")
  .toBuffer('PNG', function(err, buffer) {
    if (err) return handle(err);
    console.log('done!');
    gm(buffer, 'image.png')
      .composite('avatar.png')
      .geometry("200x200+50+50!")
      .write('output.png', function(err) {
        console.log(err);
      });
  });

Good luck!

Josh H
  • 264
  • 1
  • 10
0

Like Josh H said in his answer, it looks like I need to resize avatar.png separately, and then compose it with bg.png. Here's my final code:

gm("avatar.png")
    .resize(200, 200)
    .write("resizedAvatar.png", () => {
        gm("bg.png")
            .composite("resizedAvatar.png")
            .geometry("+50+50")
            .toBuffer("PNG", (err, buffer) => {
                // do whatever with `buffer`
            });

    });
APixel Visuals
  • 1,508
  • 4
  • 20
  • 38