Nikolas
Nikolas

Reputation: 85

how to put transparent image to another image using PIL without .paste() class

I'm newbie in PIL so for me it's hard to understand how I can do it, somebody helps me with it. In code, I only take two pictures and resized a transparent one. Now I don't know what to do next to paste it without .paste() class

def get_web_image (url):
    img_data = requests.get(url).content
    with open('picture1(bg)_1200x800.png', 'wb') as handler:
        handler.write(img_data)
    return img_data


def paste_image (source, destination, x, y, omit_color="None"):
    im = Image.open(source)
    pixels_newpaste = []
    newsize = (200, 200)
    im = im.resize(newsize)
    im.save('picture2(done).png')
    im.show()



paste_image ('picture2(transparent)_840x841.png', main_image, 1, 1)
main_pic()
#my_img_object = get_web_image ('https://avante.biz/wp-content/uploads/Baseball-Wallpapers/Baseball-Wallpapers-015.jpg')

enter image description here

enter image description here

I tried to make it using .getpixel(), but as I understand it requires only to draw in one color. So please help me to make this function

Upvotes: 2

Views: 590

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

Here is a simplified version using these two images which are suitably resized and also partially transparent:

enter image description here

enter image description here

#!/usr/bin/env python3

from PIL import Image

# Open pitcher and pitch images
bg = Image.open('pitch.jpg')
fg = Image.open('pitcher.png').convert('RGBA')
w, h = fg.width, fg.height

# Iterate over rows and columns
for y in range(h):
   for x in range(w):
      # Get components of foreground pixel
      r, g, b, a = fg.getpixel((x,y))
      # If foreground is opaque, overwrite background with foreground
      if a>128:
          bg.putpixel((x,y), (r,g,b))

# Save result    
bg.save('result.png')

enter image description here

Upvotes: 2

Related Questions