Home > OS >  How to add dotted or dashed line to png in Python?
How to add dotted or dashed line to png in Python?

Time:06-28

Hello I want a draw a dashed or dotted line to png, I couldn't find How can I do that, Can someone help ?

im = Image.new('RGB', (2000,2000),tuple(int(hex_color[i:i 2], 16) for i in (0, 2, 4))) print("...Saving...") im.save('C:\\Users\\th3m1s\\Desktop\\Lejant\\' str(legend_code) '.png', quality=100) Result is click here

CodePudding user response:

Have you considered creating a new image with vertical lines as well as horizontal lines, slightly taller and wider than your original image, on which you paste your original image? That way you will have a dotted border and it works for every size.

This can be done as explained here: How do you composite an image onto another image with PIL in Python?

from PIL import Image,ImageDraw
#this is your own image
yourimage = Image.open('/home/vancha/Documenten/python/pillu/square.png', 'r')
img_w, img_h = yourimage.size
border_width = 5
#this is the new image which holds the stripes
borderimage = Image.new('RGBA', (2000 (border_width * 2), 2000 (border_width *2)), (255, 255, 255, 255))


# Draw the lines
draw = ImageDraw.Draw(borderimage)
#starts drawing vertical lines form the very top
start = 0
end = borderimage.height#width or height, doens't matter since the image is square
step_size = border_width*4

#starts from border_width * 2, so that the very top and very left aren't made black with lines
for x in range(border_width*2, borderimage.width, step_size):
    vertical_line = ((x, start), (x, end))
    #the width is the thickness of the "dots" in the border
    draw.line(vertical_line, fill=(0,0,0),width=border_width * 2)

    horizontal_line = ((start,x), (end, x))
    draw.line(horizontal_line, fill=(0,0,0),width=border_width *2)

#for good practice:
del draw


bg_w, bg_h = borderimage.size
#calculate the offset so that the image is centered
offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)

#paste your old image over the one with the dots
borderimage.paste(yourimage, offset)

#save it wherever you want :)
borderimage.save('./border.png')

In your case, if you want your border to be 5px all the way around your image, and your image is 2000,2000, changing the size of the new image to be 2010 by 2010 leaves you with 5px to spare on both sides if you paste your own image in the center.

  • Related