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

时间:2017-05-24 12:58:11

标签: python image rotation python-imaging-library

由于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()

我明白了:

output image

1 个答案:

答案 0 :(得分:3)

在粘贴时尝试添加mask,如下所示:

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

e.g。

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()

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

ellipses