ArrayCreator
ArrayCreator

Reputation: 93

Merging two images in to one in pygame

I have a program that takes two different images - one a tile texture (32x32) that has no blank/transparent spots and the second one is an effect (cracks effect) that has transparent pixels and it is also 32x32 . From those two images i want to make one.

I tried placing the second image on the first one but it did not work (i thing i don't let the transparency work in it)

First of all - how do i get the transparency to work on an image in pygame(any color key) and different opacity's. and Second thing is - How do i merge them?

Upvotes: 2

Views: 7127

Answers (1)

sloth
sloth

Reputation: 101042

To "merge" two images, just blit the second one onto the first one.

Given these two images (1.png, 2.png)

1.png 2.png

here's an example:

import pygame

pygame.init()
screen = pygame.display.set_mode((200, 50))

image = pygame.image.load("1.png")
shadow = pygame.image.load("2.png")

merged = image.copy()
merged.blit(shadow, (0, 0))

while True:  
    screen.fill(pygame.color.Color('white'))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise

    screen.blit(image, (0,  0))                
    screen.blit(shadow, (50, 0))
    screen.blit(image, (100, 0))
    screen.blit(shadow, (100, 0))
    screen.blit(merged, (150, 0))
    pygame.display.flip()

Result:

enter image description here

If that does not work for you, your surfaces may have different pixel formats. Fix that by calling convert_alpha on each surface.

If your problem is about mixing surfaces with a color key and surfaces with per-pixel transparency, take a look at this answer.

Upvotes: 6

Related Questions