Skip to content

How do I overlay successive images without resorting to using buffers? #971

Closed

Description

@djalbat

Hi,

I've just discovered sharp. I'm eternally grateful!

I'm trying to overlay many images onto a single image in order to create an image map.

I've gotten this far...

sharp({
  create: {
    width: 512,
    height: 512,
    channels: 4,
    background: {
      r: 255,
      g: 255,
      b: 255,
      alpha: 255
    }
  }
}).png()
.overlayWith(grassImagePath, {
  top: 0,
  left: 0
})
.pipe(response)

...but naïvely trying to overlay successive images...

sharp({
  create: {
    width: 512,
    height: 512,
    channels: 4,
    background: {
      r: 255,
      g: 255,
      b: 255,
      alpha: 255
    }
  }
}).png()
.overlayWith(grassImagePath, {
  top: 0,
  left: 0
})
.overlayWith(concreteImagePath, {
  top: 0,
  left: 0
})
.pipe(response)

...does not seem to work.

I've found a way around this by using buffers:

sharp({
  create: {
    width: 512,
    height: 512,
    channels: 4,
    background: {
      r: 255,
      g: 255,
      b: 255,
      alpha: 255
    }
  }
}).png()
.toBuffer()
.then(function(buffer) {
  sharp(buffer)
  .overlayWith(grassImagePath, {
    top: 0,
    left: 0
  })
  .toBuffer()
  .then(function(buffer) {
    sharp(buffer)
    .overlayWith(concreteImagePath, {
      top: 256,
      left: 0
    })
    .pipe(response)
  })
});

I can remove the pyramid with some asynchronous utility function, after all this will be working on an array of images, but I still feel that using buffers like this is wasteful.

So my question is: is there a way to apply successive overlays without resorting to this kind of trickery?

Activity

  1. lovell commented on Oct 1, 2017

    @lovell
    Owner

    Hello, did you see #728 ?

  2. djalbat commented on Oct 1, 2017

    @djalbat
    Author

    I'll close it myself if that's okay since I'm here. Thanks again.

  3. simeyla commented on Jun 26, 2018

    @simeyla

    Until #405 is complete it makes for cleaner code to do the following and use await instead of a nasty promise chain. Then when the feature is completed you can just kill off those two lines.

     sharpImage.overlayWith(.....);
    
     var tempBuffer = await compressedImage.toBuffer({ resolveWithObject: true });
     sharpImage = sharp(tempBuffer.data);
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions