Sharp: overlay image

Created on 25 Nov 2016  路  2Comments  路  Source: lovell/sharp

First I would like to congratulate you for this amazing lib !

I have just a question regarding the overlay feature.

It says in the docs that ".overlayWith" can take a path or a Buffer. But it doesn't think to work for me, maybe I got it wrong.

I'm trying to take an image, make it blur and set it as background and then adding the same picture on top of it, to give the same effect (see uploaded file).

1480064386406_bg

var sharp = require('sharp');
var date = Date.now();

var img = sharp('base2.jpg');
var background = img.clone();

img
    .resize(800, 533)
    .max()
    .quality(80)
    .toFormat(sharp.format.jpeg)
    .toFile('img/' + date + '_face.jpg', function(err, info) {
        if(err) return console.log(err);

        background
            .resize(800, 533)
            .quality(80)
            .blur(15)
            .quality(85)
            .toFormat(sharp.format.jpeg)
            .overlayWith('img/' + date + '_face.jpg')
            .toFile('img/' + date + '_bg.jpg');
    });

The problem is that I have to save the file to be able to use it again. Are there any other solution to do it in one time ?

Thanks :)

cookbook question

Most helpful comment

You could convert the image to a buffer and use that as input for overlayWith.

Example:

const sharp = require('sharp');
const fs = require('fs');

const resize = sharp()
  .resize(800, 533)
  .max()
  .quality(80)
  .toFormat(sharp.format.jpeg);

const blurResize = sharp()
  .resize(800, 533)
  .quality(80)
  .blur(15)
  .quality(85)
  .toFormat(sharp.format.jpeg);

fs.createReadStream('leslie.jpg')
  .pipe(resize.toBuffer((err, buffer) => {
    if (err) return console.log(err);

    fs.createReadStream('leslie.jpg')
      .pipe(blurResize.overlayWith(buffer))
      .pipe(fs.createWriteStream('leslie.overlayed.jpg'));
  }));

It uses two read streams though.

Example output:
leslie overlayed

All 2 comments

You could convert the image to a buffer and use that as input for overlayWith.

Example:

const sharp = require('sharp');
const fs = require('fs');

const resize = sharp()
  .resize(800, 533)
  .max()
  .quality(80)
  .toFormat(sharp.format.jpeg);

const blurResize = sharp()
  .resize(800, 533)
  .quality(80)
  .blur(15)
  .quality(85)
  .toFormat(sharp.format.jpeg);

fs.createReadStream('leslie.jpg')
  .pipe(resize.toBuffer((err, buffer) => {
    if (err) return console.log(err);

    fs.createReadStream('leslie.jpg')
      .pipe(blurResize.overlayWith(buffer))
      .pipe(fs.createWriteStream('leslie.overlayed.jpg'));
  }));

It uses two read streams though.

Example output:
leslie overlayed

@anasbud I hope @makepanic's excellent answer helped. Please feel free to re-open if not.

Was this page helpful?
0 / 5 - 0 ratings