Comprehensive Guide to Merging Images with merge-img – A Step-by-Step Tutorial for Developers

Introduction to merge-img

The merge-img library is a versatile and efficient tool for combining multiple images into one, making it ideal for developers working on image processing projects. This guide covers essential APIs and usage examples to help you understand and utilize merge-img effectively.

Installing merge-img

  npm install merge-img

Basic Usage

Let’s start with a basic example to merge two images.

  
    const mergeImg = require('merge-img');

    mergeImg(['image1.png', 'image2.png'])
      .then((img) => {
        img.write('out.png', () => console.log('Image saved!'));
      });
  

API Examples

Horizontal Merge

  
    mergeImg(['image1.png', 'image2.png'])
      .then((img) => {
        img.write('horizontal_merge.png');
      });
  

Vertical Merge

  
    mergeImg(['image1.png', 'image2.png'], { direction: true })
      .then((img) => {
        img.write('vertical_merge.png');
      });
  

Adding Margin

  
    mergeImg(['image1.png', 'image2.png'], { margin: 10 })
      .then((img) => {
        img.write('margin_merge.png');
      });
  

Adjusting Color

  
    mergeImg(['image1.png', 'image2.png'], { color: 0xcccccc })
      .then((img) => {
        img.write('color_merge.png');
      });
  

Using Buffer

  
    const fs = require('fs');
    const mergeImg = require('merge-img');

    const img1Buffer = fs.readFileSync('image1.png');
    const img2Buffer = fs.readFileSync('image2.png');

    mergeImg([img1Buffer, img2Buffer])
      .then((img) => {
        img.write('buffer_merge.png');
      });
  

Overlay Images

  
    mergeImg([{
      src: 'image1.png',
      x: 0,
      y: 0,
    }, {
      src: 'image2.png',
      x: 50,
      y: 50,
    }])
      .then((img) => {
        img.write('overlay_merge.png');
      });
  

Practical App Example

Below is a practical example where we use the merge-img library to create a thumbnail image from various sources.

  
    const express = require('express');
    const mergeImg = require('merge-img');

    const app = express();

    app.get('/thumbnail', (req, res) => {
      mergeImg(['avatar.png', 'frame.png'])
        .then((img) => {
          img.getBuffer('image/png', (err, buffer) => {
            if (err) {
              res.status(500).send(err);
            } else {
              res.set('Content-Type', 'image/png');
              res.send(buffer);
            }
          });
        });
    });

    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
  

This server listens on port 3000 and merges images on the fly when the /thumbnail endpoint is accessed.

Hash: 3cba4a7b5b53872100f271f88929174eb4d5ceefcde9540d510f1d15a38b9bfb

Leave a Reply

Your email address will not be published. Required fields are marked *