使用 PIL 的粘贴方法时出现透明度问题

Transparency issue while using PIL's paste method

由于PIL 似乎无法创建一个有角度的椭圆,所以我编写了一个函数来执行此操作。问题是,当我使用 PIL 粘贴时,它似乎没有使用 alpha 信息。有谁知道如果所有图像都是 RGBA,为什么要删除透明度信息?

提前致谢!:

from PIL import Image, ImageDraw

def ellipse_with_angle(im,x,y,major,minor,angle,color):
    # take an existing image and plot an ellipse centered at (x,y) with a 
    # defined angle of rotation and major and minor axes.
    # center the image so that (x,y) is at the center of the ellipse
    x -= int(major/2) 
    y -= int(major/2) 

    # create a new image in which to draw the ellipse
    im_ellipse = Image.new('RGBA', (major,major), (255,255,255,0))
    draw_ellipse = ImageDraw.Draw(im_ellipse, "RGBA")
    
    # draw the ellipse
    ellipse_box = (0,int(major/2-minor/2),major,int(major/2-minor/2)+minor)
    draw_ellipse.ellipse(ellipse_box, fill=color)

    # rotate the new image
    rotated = im_ellipse.rotate(angle)
    rx,ry = rotated.size
    
    # paste it into the existing image and return the result
    im.paste(rotated, (x,y,x+rx,y+ry))    
    return im

如果我尝试这样调用它:

im = Image.new('RGBA', (500,500), (40,40,40,255))
im = ellipse_with_angle(im,x=250,y=250,major=300,minor=200,angle=60,color=(255,0,0,255))
im = ellipse_with_angle(im,x=300,y=200,major=100,minor=75,angle=130,color=(255,0,255,150))
im = make_color_transparent(im,(0,0,0,255))
im.show()

我明白了:

尝试在粘贴时添加一个mask如下:

im.paste(rotated, (x,y,x+rx,y+ry), mask=rotated) 

例如

from PIL import Image, ImageDraw

def ellipse_with_angle(im,x,y,major,minor,angle,color):
    # take an existing image and plot an ellipse centered at (x,y) with a 
    # defined angle of rotation and major and minor axes.
    # center the image so that (x,y) is at the center of the ellipse
    x -= int(major/2) 
    y -= int(major/2) 

    # create a new image in which to draw the ellipse
    im_ellipse = Image.new('RGBA', (major,major), (255,255,255,0))
    draw_ellipse = ImageDraw.Draw(im_ellipse, "RGBA")

    # draw the ellipse
    ellipse_box = (0,int(major/2-minor/2),major,int(major/2-minor/2)+minor)
    draw_ellipse.ellipse(ellipse_box, fill=color)

    # rotate the new image
    rotated = im_ellipse.rotate(angle)
    rx,ry = rotated.size

    # paste it into the existing image and return the result
    im.paste(rotated, (x,y,x+rx,y+ry), mask=rotated)    
    return im


im = Image.new('RGBA', (500,500), (40,40,40,255))
im = ellipse_with_angle(im,x=250,y=250,major=300,minor=200,angle=60,color=(255,0,0,255))
im = ellipse_with_angle(im,x=300,y=200,major=100,minor=75,angle=130,color=(255,0,255,150))
#im = make_color_transparent(im,(0,0,0,255))
im.show()

哪个应该给你这样的东西: