2

I'd like to take one image and composite it on top of another image.

This works well for that purpose:

overlayImg = await Sharp(sourceImage.Body)
            .composite([{ 
                input: './lambdas/processNewImage/logos/white.png', 
                gravity: 'southeast',
                
            }])
            .toFormat('jpeg').toBuffer();

I also have a variable - 1-100 that is supposed to be the opacity of the watermark. Sometimes I want it full solid At 100% opacity, others 70% and others 30%...etc. Because I need this to be variable, I cannot just change the opacity of the watermark image.

I cannot figure out how to change the opacity of a composited image in Sharp.

Can any one give a quick example?

lowcrawler
  • 6,777
  • 9
  • 37
  • 79

2 Answers2

4

Found this in another thread where you overlay with a raw pixel buffer containing tiled, semi-transparent pixel value. 128 means 50% opacity where valid values are 0-255. https://github.com/lovell/sharp/issues/554

overlayImg = await Sharp(sourceImage.Body)
  .composite([
    { 
      input: './lambdas/processNewImage/logos/white.png', 
      gravity: 'southeast',  
    },
    {
      input: Buffer.from([0,0,0,128]),
      raw: {
        width: 1,
        height: 1,
        channels: 4,
      },
      tile: true,
      blend: 'dest-in',
    }
  ])
  .toFormat('jpeg').toBuffer();
Paintoshi
  • 816
  • 10
  • 12
0

Sharp can change the alpha channel (opacity) of an image. https://sharp.pixelplumbing.com/api-channel#ensurealpha

sharp(current_path + 'logo.png')
  .ensureAlpha(0.5) // 50% opacity 
  .toBuffer()
  .then(transparent_logo=>{

      sharp(current_path + 'photo.png')
             .composite([{input: transparent_logo }])
             .toFile(current_path + 'output.png');
  })
Timar Ivo Batis
  • 1,861
  • 17
  • 21
  • This approach would work with JPG images but not PNG. `ensureAlpha` _ensures_ an alpha channel. If the image already has an alpha channel then nothing will happen. – Payton Doud May 18 '23 at 15:08