Fix PIL.ImageDraw.Draw.line with wide lines

Viewed 5206

From the PIL Documentation:

PIL.ImageDraw.Draw.line(xy, fill=None, width=0)

Draws a line between the coordinates in the xy list.

Parameters:

  • xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or numeric values like [x, y, x, y, ...].
  • fill – Color to use for the line.
  • width – The line width, in pixels. Note that line joins are not handled well, so wide polylines will not look good.

I'm looking for a fix for this issue. A good solution for me would be to have the line drawn by PIL.ImageDraw have rounded ends (capstyle in TKinter). Is there an equivalent in PIL.ImageDraw?

This is what I would like to obtain: enter image description here

Minimal Working Example:

from PIL import Image, ImageDraw

WHITE = (255, 255, 255)
BLUE = "#0000ff"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)

MyDraw.line([100,100,150,200], width=40, fill=BLUE)
MyDraw.line([150,200,300,100], width=40, fill=BLUE)
MyDraw.line([300,100,500,300], width=40, fill=BLUE)

MyImage.show()

Result from MWE:

enter image description here

2 Answers

There are standard option joint='curve' of the ImageDraw.line designed to fix it.

Your example may look like

from PIL import Image, ImageDraw

WHITE = (255, 255, 255)
BLUE = "#0000ff"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)

line_points = [(100, 100), (150, 200), (300, 100), (500, 300)]
MyDraw.line(line_points, width=40, fill=BLUE, joint='curve')

MyImage.show()

Special care is required to address the end-points, but joints are fixed.

The result:

Fixed line with joint='curve'

Related