如何在Python中添加虚线或虚线到png ?



你好,我想画一个虚线或虚线到png,我找不到我怎么能做到这一点,有人可以帮助吗?

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)结果是点击这里

您是否考虑过创建一个新图像,其中包含竖线和水平线,比原始图像稍高和稍宽,然后粘贴原始图像?这样你就会有一个虚线边框,它适用于任何尺寸。

可以这样做:如何在Python中使用PIL将一个图像合成到另一个图像上?

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')

在你的例子中,如果你想让你的图像周围的边框都是5px,你的图像是2000,2000,改变新图像的大小为2010 × 2010,如果你粘贴你自己的图像在中心,你就会有5px的多余空间。

最新更新