python PIL模塊在圖片畫線寫字

圖片上畫線條

import sys
from PIL import Image,ImageDraw

im = Image.open("th.png")
draw = ImageDraw.Draw(im) #實例化一個對象
draw.line((0, 0) + im.size, fill=128, width=5)  #線的起點和終點,線寬
draw.line((0, im.size[1], im.size[0], 0), fill=128)
draw.line((0,im.size[1]/2)+(im.size[0]/2,im.size[1]), fill=128, width=5)
im.show()

圖片上寫字

from PIL import Image, ImageDraw, ImageFont

# get an image
base = Image.open('th.jpg').convert('RGBA')
# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255,255,255,0))
# get a font  需要在C:\Windows\Fonts拷貝一份字體文件 當前腳本路徑下
fnt = ImageFont.truetype('cambriai.ttf', 40)
# get a drawing context
d = ImageDraw.Draw(txt)
# draw text, half opacity
d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))
# draw text, full opacity
d.text((10,60), "World", font=fnt, fill=(255,255,255,255))
fillcolor = "#ff0000"   #字體顏色
d.text((base.size[0]-20,10), "4", font=fnt, fill=fillcolor)
out = Image.alpha_composite(base, txt)
out.show()   

參考官方文檔 https://pillow.readthedocs.io/en/stable/reference/Image.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章