How to insert a PNG without background to another PNG in PYVIPS?

121 views Asked by At

I have two png images with transparent background

example:

image_0

image_1

and I'm trying to achieve something similar to the PIL paste() function in pyvips, where I can merge two images and 'remove the transparent background' using a mask.

PIL example:

image = Image.open(filepath, 'r')
image_2 = Image.open(filepath, 'r')
image.paste(image_2, (50, 50), mask=mask)

Expected Result:

expected result

I've already tried to use the pyvips insert() function, but both images retain their backgrounds.

Pyvips insert:

image = pyvips.Image.new_from_file(path, access='sequential')
image_2 = pyvips.Image.new_from_file(path, access='sequential')
image = image.insert(image_2, 50,50)

Pyvips Result:

pyvips result

How can I have the "expected result" with pyvips?

1

There are 1 answers

2
Mark Setchell On BEST ANSWER

You can do it like this, using the composite() function:

import pyvips

# Load background and foreground images
bg = pyvips.Image.new_from_file('WA8rm.png', access='sequential')
fg = pyvips.Image.new_from_file('Ny50t.png', access='sequential')

# Composite foreground over background and save result
bg.composite(fg, 'over').write_to_file('result.png')

enter image description here


If you want to add an offset in x and y, use:

bg.composite(fg, 'over', x=200, y=100).write_to_file('result.png')

enter image description here