write function on python using pil library wich adds one transparent image to another
- User
write function on python using pil library wich adds one transparent image to another
- Assistant
To overlay one transparent image over another using the Python Imaging Library (PIL), you'll typically use the
Pillowpackage, which is an actively maintained fork of PIL. Here's a function that takes two image paths and overlays the second (transparent) image onto the first. Ensure that you have installed Pillow in your environment (pip install Pillow) before running the code.Here's the function:
pythonfrom PIL import Image def overlay_images(background_image_path, overlay_image_path, position=(0, 0), output_path='output.png'): """ Overlays a transparent image onto another image. :param background_image_path: Path to the background image. :param overlay_image_path: Path to the overlay image (must have transparency). :param position: Tuple (x, y) indicating the position to place the overlay image on the background. :param output_path: Path to save the resulting image. """ # Open the background and overlay images background = Image.open(background_image_path).convert('RGBA') overlay = Image.open(overlay_image_path).convert('RGBA') # Create a new image with the same size as the background combined = Image.new('RGBA', background.size) # Paste the background combined.paste(background, (0, 0)) # Paste the overlay image on top of the background image, using itself as a mask combined.paste(overlay, position, overlay) # Save the result to the specified output path combined.save(output_path, format='PNG') print(f"Image saved to {output_path}") # Example usage: # overlay_images('background.png', 'overlay.png', position=(50, 50), output_path='output.png')Explanation:
- User
How to change image transparency and add it to another image using pil?
- Assistant