PIL簡介:
python平台事實上的圖片處理標准庫,功能強大,API簡單易用
PIL安裝:
pip install PIL
直接繪圖插入文字
#!/usr/bin/env python from PIL import Image, ImageDraw, ImageFont, ImageFilter # 240 x 60: width = 60 * 4 height = 60 image = Image.new('RGB', (width, height), (255, 255, 255)) # 創建Font對象: font = ImageFont.truetype('Arial.ttf', 36) # 創建Draw對象: draw = ImageDraw.Draw(image)
text = '你要插入的文字'
# 輸出文字: for t in range(4):
position =(60 * t + 10, 10)
draw.text(position, text, font=font, fill="#000000", spacing=0, align='left')
image.save('code.jpg', 'jpeg');
打開已有的圖片插入文字
#!/usr/bin/env python from PIL import Image, ImageDraw, ImageFont, ImageFilter image = Image.open('cat.jpg') # 創建Font對象: font = ImageFont.truetype('Arial.ttf', 36) # 創建Draw對象: draw = ImageDraw.Draw(image) text = '你要插入的文字' # 輸出文字: for t in range(4): position =(60 * t + 10, 10) draw.text(position, text, font=font, fill="#000000", spacing=0, align='left') image.save('code.jpg', 'jpeg');
封裝成方法
def insert_text(text, fone_type_file, font_size, im, position): ''' ** text 要插入的文字 ** fone_type_file 文字類型文件名稱 ** font_size 文字大小 ** im 背景圖片 ** position 要插入的位置 ''' datas = text.split('\n') data = '' if not datas: datas = [text] for d in datas: if not d: d = ' ' elif len(d) > 31: d1 = d[:30] + '\n' d2 = d[30:] d = d1 + ' \n'+ d2 data += (d +'\n') data += ' \n' data = data[:-1] dr = ImageDraw.Draw(im) font = ImageFont.truetype(fone_type_file, font_size) dr.text(position, data, font=font, fill="#000000", spacing=0, align='left') im.save("t.png") return im, len(datas)