How to paste an image onto a larger image using Pillow?

前端 未结 2 815
一生所求
一生所求 2020-12-14 18:53

I\'ve got a fairly simple code file:

from PIL import Image
til = Image.new(\"RGB\",(50,50))
im = Image.open(\"tile.png\") #25x25
til.paste(im)
til.paste(im,(         


        
2条回答
  •  我在风中等你
    2020-12-14 19:21

    So I might be a little late, but maybe it helps the people coming after a little:

    When I had the same issue I couldn't find much about it. So I wrote a snippet which pastes one image into another.

    def PasteImage(source, target, pos):
    
        # Usage:
        # tgtimg = PIL.Image.open('my_target_image.png')
        # srcimg = PIL.Image.open('my_source_image.jpg')
        # newimg = PasteImage(srcimg, tgtimg, (5, 5))
        # newimg.save('some_new_image.png')
        #
    
        smap = source.load()
        tmap = target.load()
        for i in range(pos[0], pos[0] + source.size[0]): # Width
            for j in range(pos[1], pos[1] + source.size[1]): # Height
                # For the paste position in the image the position from the top-left
                # corner is being used. Therefore 
                # range(pos[x] - pos[x], pos[x] + source.size[x] - pos[x])
                # = range(0, source.size[x]) can be used for navigating the source image.
    
                sx = i - pos[0]
                sy = j - pos[1]
    
                # Change color of the pixels
                tmap[i, j] = smap[sx, sy]
    
        return target
    

    Not necessarely the best approach, since it takes roughly O(N^2), but it works for small images. Maybe someone can improve the code to be more efficient.

    I made it in a hurry, so it doesnt have input validation either. just know that the width and height of the source image MUST be smaller or equal to width and height of the target image, otherwise it will crash. You can also only paste the whole image, and not sections or non-rectangular images.

提交回复
热议问题