2

I want to draw a dotted rectangle using PIL.

I know I can draw 4 different dotted lines to make it look like a rectangle with this:

for x in range(0, Width_of_image, 5):
    d.line([(x, 30), (x + 2, 30)],fill ="black", width =2) 

But is there any way to draw a rectangle using draw.rectangle, i.e., without drawing 4 different line?

Noob Geek
  • 409
  • 6
  • 20

4 Answers4

9

Like other users said, PIL library (specifically PIL.ImageDraw.ImageDraw) doesn't provide the functionality to draw dashed lines. I looked at StackOverflow questions (and other places) about dashed lines in PIL, but I haven't found a satisfactory way to draw a dashed line in PIL. None of the answers I have found didn't draw the dashed line in the expected way (the way other Python libraries provide dashed lines, for example using Tkinter canvas).

So I wrote class DashedImageDraw (which extends PIL.ImageDraw.ImageDraw) which has functionality to draw dashed line and dashed rectangle. Here are the code and an example of how to use it:

from PIL import Image, ImageDraw
import math


class DashedImageDraw(ImageDraw.ImageDraw):

    def thick_line(self, xy, direction, fill=None, width=0):
        #xy – Sequence of 2-tuples like [(x, y), (x, y), ...]
        #direction – Sequence of 2-tuples like [(x, y), (x, y), ...]
        if xy[0] != xy[1]:
            self.line(xy, fill = fill, width = width)
        else:
            x1, y1 = xy[0]            
            dx1, dy1 = direction[0]
            dx2, dy2 = direction[1]
            if dy2 - dy1 < 0:
                x1 -= 1
            if dx2 - dx1 < 0:
                y1 -= 1
            if dy2 - dy1 != 0:
                if dx2 - dx1 != 0:
                    k = - (dx2 - dx1)/(dy2 - dy1)
                    a = 1/math.sqrt(1 + k**2)
                    b = (width*a - 1) /2
                else:
                    k = 0
                    b = (width - 1)/2
                x3 = x1 - math.floor(b)
                y3 = y1 - int(k*b)
                x4 = x1 + math.ceil(b)
                y4 = y1 + int(k*b)
            else:
                x3 = x1
                y3 = y1 - math.floor((width - 1)/2)
                x4 = x1
                y4 = y1 + math.ceil((width - 1)/2)
            self.line([(x3, y3), (x4, y4)], fill = fill, width = 1)
        return   
        
    def dashed_line(self, xy, dash=(2,2), fill=None, width=0):
        #xy – Sequence of 2-tuples like [(x, y), (x, y), ...]
        for i in range(len(xy) - 1):
            x1, y1 = xy[i]
            x2, y2 = xy[i + 1]
            x_length = x2 - x1
            y_length = y2 - y1
            length = math.sqrt(x_length**2 + y_length**2)
            dash_enabled = True
            postion = 0
            while postion <= length:
                for dash_step in dash:
                    if postion > length:
                        break
                    if dash_enabled:
                        start = postion/length
                        end = min((postion + dash_step - 1) / length, 1)
                        self.thick_line([(round(x1 + start*x_length),
                                          round(y1 + start*y_length)),
                                         (round(x1 + end*x_length),
                                          round(y1 + end*y_length))],
                                        xy, fill, width)
                    dash_enabled = not dash_enabled
                    postion += dash_step
        return

    def dashed_rectangle(self, xy, dash=(2,2), outline=None, width=0):
        #xy - Sequence of [(x1, y1), (x2, y2)] where (x1, y1) is top left corner and (x2, y2) is bottom right corner
        x1, y1 = xy[0]
        x2, y2 = xy[1]
        halfwidth1 = math.floor((width - 1)/2)
        halfwidth2 = math.ceil((width - 1)/2)
        min_dash_gap = min(dash[1::2])
        end_change1 = halfwidth1 + min_dash_gap + 1
        end_change2 = halfwidth2 + min_dash_gap + 1
        odd_width_change = (width - 1)%2        
        self.dashed_line([(x1 - halfwidth1, y1), (x2 - end_change1, y1)],
                         dash, outline, width)       
        self.dashed_line([(x2, y1 - halfwidth1), (x2, y2 - end_change1)],
                         dash, outline, width)
        self.dashed_line([(x2 + halfwidth2, y2 + odd_width_change),
                          (x1 + end_change2, y2 + odd_width_change)],
                         dash, outline, width)
        self.dashed_line([(x1 + odd_width_change, y2 + halfwidth2),
                          (x1 + odd_width_change, y1 + end_change2)],
                         dash, outline, width)
        return
        


image = Image.new('RGB', (300, 200), (255, 255, 255))
d = DashedImageDraw(image)

d.dashed_rectangle([(20, 20), (280, 180)],
                   dash = (5, 3), outline  = 'black', width = 2)

image.save("image.png", "PNG")

This line draws the ractangle:

d.dashed_rectangle([(20, 20), (280, 180)], dash = (5, 3), outline  = 'black', width = 2)

(20, 20) is the top left corner, (280, 180) is the bottom right corner, outline is the color of the line, width is the width of the line, and dash is a tuple representing dash pattern. For example:

  • dash = (5, 3) will draw line:

    ----- ----- ----- ----- ----- -----

  • dash = (4, 2, 3, 1) will draw line:

    ---- --- ---- --- ---- --- ---- --- ----

This the image of the dashed rectangle produced by the code above:

Dashed rectangle

ands
  • 1,926
  • 16
  • 27
  • Thanks for your implementation. It works fine for horizontal and vertical lines, but is prone to errors on angled lines – Sifi_crafter May 12 '23 at 11:37
0

I have no experience in PIL, but quite a lot of python overall, and if you do want to use PIL, there is a link to a question on dotted lines in PIL. Other Python modules you can use to draw dotted lines are things such as: Turtle, Pygame or, if using Tkinter, you can add the line self.canvas.itemconfig(line, dash=(4, 4)) into your work to make it a dashed line.

Max
  • 21
  • 8
-2

It isn't possible directly. You can create your own def and draw for dotted lines there

Christoph S.
  • 585
  • 3
  • 16
-2

Even though i have no experience with PIL or "d", i suggest you just create a new function that takes in width_of_image and other possible arguments and perform what you described in the question

def dotted_rect(width_of_image, **kwargs):
    for x in range(0, width_of_image, 5):
        d.line([(x, 30), (x+2,30)], **kwargs)