Is it possible to create a tile 2×2 mosaic using Sharp Node?

Issue

Using Image Magick I was able to use montage to make this:

enter image description here

With this code:

montage -density 300 -tile 2x0 -geometry 150x150^ -gravity center -crop 150x150+0+0 -border 0 '.$img_array.' /var/www/html/uploads/output.jpg

I would like to know if this is possible too using Sharp, I saw the tile option but I don’t understand how to use 4 different images together.

Solution

Thanks to the Author, I found this tricky solution.

Imagine you want a 2×2 mosaic with a fixed size of 400×400 pixels.

In the example below I have all my images into ./images/ folder. All 4 images are of fixed size 200×200 pixels.

You need also a background picture big enough to contain the mosaic. You can use for this any image and resize with Sharp as well.

const sharp = require('sharp');
 
sharp('./images/output4.jpg')
  .resize(400, 400)
  .toFile('bg.jpg', function(err) {
    console.log("Something wrong",err)
  });

Now that you have created the bg.jpg image you can run this JavaScript:

const sharp = require('sharp');
 
sharp('./images/bg.jpg') //here call the previous generated image
  .composite([
    { input: './images/output1.jpg', gravity: 'northwest' },
    { input: './images/output2.jpg', gravity: 'northeast' },
    { input: './images/output3.jpg', gravity: 'southwest' },
    { input: './images/output4.jpg', gravity: 'southeast' },
  ])
  .toFile('combined.jpg');

In the future will be easier with something like this (not yet implemented):

 vips arrayjoin "./images/1.jpg ./images/2.jpg ./images/3.jpg ./images/4.jpg" out.jpg --across 2

Answered By – NineCattoRules

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.