Is there a way to specify the width of a rectangle in PIL? Is there a way to specify the width of a rectangle in PIL? python python

Is there a way to specify the width of a rectangle in PIL?


UPDATE - Pillow >= 5.3.0 rectangle now supports the width argument:PIL.ImageDraw.ImageDraw.rectangle(xy, fill=None, outline=None, width=0)

Previous answer:

Here is a method that draws a first initial rectangle, and then further rectangles going inwards - note, the line width is not centered along the border.

def draw_rectangle(draw, coordinates, color, width=1):    for i in range(width):        rect_start = (coordinates[0][0] - i, coordinates[0][1] - i)        rect_end = (coordinates[1][0] + i, coordinates[1][1] + i)        draw.rectangle((rect_start, rect_end), outline = color)# example usageim = Image.open(image_path)drawing = ImageDraw.Draw(im)top_left = (50, 50)bottom_right = (100, 100)outline_width = 10outline_color = "black"draw_rectangle(drawing, (top_left, bottom_right), color=outline_color, width=outline_width)


PIL rectangle now support width parameter.

from PIL import Image, ImageDrawheight = width = 800img = Image.new('RGB', (height, width), (255, 255, 255))draw = ImageDraw.Draw(img)draw.rectangle([100,100,500,400], width = 10, outline="#0000ff")img.show()


Instead of four lines you can also draw one line with four points, making a rectangle:

def drawrect(drawcontext, xy, outline=None, width=0):    (x1, y1), (x2, y2) = xy    points = (x1, y1), (x2, y1), (x2, y2), (x1, y2), (x1, y1)    drawcontext.line(points, fill=outline, width=width)# examplefrom PIL import Image, ImageDrawim = Image.new("RGB", (150, 150), color="white")draw = ImageDraw.Draw(im)drawrect(draw, [(50, 50), (100, 100)], outline="red", width=5)im.show()