Skip to content

alpha_composite should be like paste and allow negative destinations #5298

@CarlKCarlK

Description

@CarlKCarlK

If you try to use alpha_composite with a negative dest, it produces an error message. For example:

from PIL import Image
solid_green = Image.new("RGBA",(100,100),(0,255,0,255))
semidark = Image.new("RGBA",(100,100),(0,0,0,127))

ac_result = solid_green.copy()
ac_result.alpha_composite(semidark,(-50,50))
ac_result.show()
# => ValueError: Destination must be non-negative

Contrast this with paste, which allows negative destinations:

from PIL import Image
solid_green = Image.new("RGBA",(100,100),(0,255,0,255))
semidark = Image.new("RGBA",(100,100),(0,0,0,127))

paste_result = solid_green.copy()
paste_result.paste(semidark,(-50,50),semidark)
paste_result.show() # Works but colors aren't alpha composited

Negatives do indicate clipping on the left or top but note that alpha_composite (like paste) already allows clipping on the right and bottom.

from PIL import Image
solid_green = Image.new("RGBA",(100,100),(0,255,0,255))
semidark = Image.new("RGBA",(100,100),(0,0,0,127))

ac_result = solid_green.copy()
ac_result.alpha_composite(semidark,(50,50))
ac_result.show() # Works great!

Until this issue is addressed, here is a work around:

def alpha_composite_workaround(image0, image1, dest):
    x1,y1 = dest
    if x1 >= 0 and y1 >= 0:
        image0.alpha_composite(image1, dest=(x1, y1))
    else:
        temp = Image.new("RGBA", image0.size, (0, 0, 0, 0))
        temp.paste(image1, (x1, y1))
        image0.alpha_composite(temp)

from PIL import Image
solid_green = Image.new("RGBA",(100,100),(0,255,0,255))
semidark = Image.new("RGBA",(100,100),(0,0,0,127))

ac_result = solid_green.copy()
alpha_composite_workaround(ac_result,semidark,(-50,50))
ac_result.show()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions