代码:
"""
创建壁纸:背景色,然后写非主流文字
"""
import requests
import random
import json
import time
from PIL import Image,ImageDraw,ImageFont
def get_text():
"""
:return:
"""
# 毒鸡汤和正能量
# https: // data.zhai78.com / openOneGood.php
# https: // data.zhai78.com / openOneBad.php
urls = ['https://data.zhai78.com/openOneGood.php','https://data.zhai78.com/openOneBad.php']
url = random.choice(urls)
res = requests.get(url)
res_dict = json.loads(res.text)
print(res_dict['txt'])
msg = res_dict['txt']
return msg
def form_text(msg):
"""
格式化字体,就是换行
:param msg:
:return:
"""
msg = msg.replace(",","\n\n")
msg = msg.replace(",","\n\n")
msg = msg.replace("?","\n\n")
msg = msg.replace("!","\n\n")
msg = msg.replace(";","\n\n")
msg = msg.replace("。","...\n")
return msg
def create_feizhuliu_bizhi(msg,text_font,width_and_height=(1280,720),bg_color='#CD5555',path="images/",text_color='#6699ff'):
"""
"""
# 1.首先创建一个画布
img = Image.new(mode="RGB", size=width_and_height, color=bg_color)
# 设置字体
draw = ImageDraw.Draw(img)
# 让字体在正确的位置居中显示
font_width, font_height = draw.textsize(form_text(msg), text_font)
draw.text(
(width_and_height[0]/2 + (0 - font_width - text_font.getoffset(msg)[0]) / 2,
width_and_height[1]/2 + (0 - font_height - text_font.getoffset(msg)[1]) / 2),
# (1000,0),
form_text(msg),
text_color,
text_font
)
# 保存照片
path = path + msg + ".png"
img.save(path)
img.close()
return
# 颜色集合和字体集合
text_colors = [
'#F0FFF0'
]
bg_colors = [
'#363636',
'#6C7B8B',
'#4F4F4F'
]
text_fonts = [
'华文中宋',
'华文仿宋',
'华文彩云',
'华文新魏',
'华文楷体',
'华文琥珀',
'华文细黑',
'华文细黑',
'华文细黑',
'华文行楷',
'华文隶书',
]
while True:
try:
time.sleep(random.randint(1,3))
# 字体格式
font_medium_type = 'fonts/' + random.choice(text_fonts) + '.ttf'
text_font = ImageFont.truetype(font_medium_type, 80) # 设置字体
create_feizhuliu_bizhi(
get_text()
, text_font,
bg_color=random.choice(bg_colors),
text_color=random.choice(text_colors)
)
except:
print("获取不到数据")
View Code
已经上传百度云。
-----------------------------------------------------------------------------------------------------------------------------------------