Home > Blockchain >  Draw an inverted pie slice with Pillow
Draw an inverted pie slice with Pillow

Time:12-05

As the title says. How can I draw the white part of the following image, using Pillow in Python? Assuming the background can be anything, and not known at the time I write the program (but likely not uniform black, maybe not uniform at all).

inverted pie slice

The documentation of ImageDraw does have the pieslice function which does the exact opposite of what I want. And the documentation of ImagePath doesn't mention arcs at all.

CodePudding user response:

Using method Image.composite to composite two images, one is your source image and another one draw the inverted pie slice where only the white area with alpha=1, other area all with alpha=0.

from PIL import Image, ImageDraw

def pieslice(im, w1, w2, fill="#ffffffff"):
    # Create a all transparent image
    im2 = Image.new('RGBA', (w1, w1), color="#00000000")
    draw = ImageDraw.Draw(im2, mode="RGBA")
    d = (w1 - w2) // 2
    # Draw a nontransparent box
    draw.rectangle([(d, d), (w2   d - 1, w2   d - 1)], fill=fill)
    # Draw a transparent pie slice
    draw.pieslice([(d, d), (2 * w2   d - 1, 2 * w2   d - 1)], 180, 270, fill="#00000000")
    # Get alpha layer as mask reference in method composite
    alpha = im2.getchannel("A")
    new_im = Image.composite(im2, im, alpha)
    return new_im

w1, w2 = 200, 180
# Can use any existing square image
im = Image.new('RGBA', (w1, w1), color="#000000ff")
new_im = pieslice(im, w1, w2)
new_im.show()
  • Related