Python 图片描述加在图片下面合成一张图
最近想爬一下图片,但是爬下来发现图片下面带着文字解释,这样看起来不太有美感,想着能不能将图片的文字解释,合成一张图,放在图片下面
先看图片格式我想要这样的效果
下面的描述接在图片上面
参考大神的生成图片写的
直接上代码
#文字生成图片,得有固定的宽度和文字字符串
def make_text_image(width,text):
#450对20号字体
fontsize = int(width*20/450)
# 创建Font对象:
font = ImageFont.truetype('C:\Windows\Fonts\微软雅黑\msyhl.ttc', fontsize)
#20号字体
txt = Image.new('RGB', (100, 100), (255, 255, 255))
# 创建Draw对象:
draw = ImageDraw.Draw(txt)
# 所有文字的段落
duanluo = ""
# 宽度总和
sum_width = 0
# 几行 一开始设置俩行是因为这个有行间距的,我弄了一下午也没搞清楚行间距怎么算
#求大神教教我
line_count = 2
# 行高
line_height = 0
#总长
duanluoheight = 0
for char in text:
#看下每个字的长和宽
char_width, height = draw.textsize(char,font=font)
sum_width += char_width
if(height > line_height):
#这个每个字符的高度不一样,找出那个最高的
line_height = height
#如果超过了规定的长度那就换行
if sum_width > width-fontsize*2:
line_count += 1
sum_width = 0
duanluo += '\n'
#将生成一个带有换行的字符串
duanluo += char
#后面再加上一个换行
if not duanluo.endswith('\n'):
duanluo += '\n'
#可以求出段落的高度
duanluoheight = line_count*line_height
#生成图片
image = Image.new('RGB', (width, duanluoheight), (255, 255, 255))
draw = ImageDraw.Draw(image)
x, y = char_width/2, 0
# 输出文字:
draw.text((x, y), duanluo, font=font, fill=(0,0,0))
# image.save('code.jpg', 'jpeg')
return image,duanluoheight
合成图片看了挺多,思路都是先造一个大的,再往里面加两个小的