1. import io
  2. import qrcode
  3. import requests
  4. from PIL import Image, ImageFont, ImageDraw, ImageOps
  5.  
  6.  
  7. def gen_poster():
  8.     """生成分享海报"""
  9.     # 读取头像
  10.     head_url = 'http://xxxxxxxxx'  # 头像
  11.     head_res = requests.get(head_url)
  12.     head_image = Image.open(io.BytesIO(head_res.content))
  13.     head_image = head_image.resize((120, 120))  # 设定图片大小
  14.  
  15.     # 读取背景图
  16.     back_image = 'https://xxx.jpeg'  # 背景
  17.     back_res = requests.get(back_image)
  18.     back_image = Image.open(io.BytesIO(back_res.content))
  19.     back_image = back_image.resize((1080, 1920))  # 设定图片大小
  20.  
  21.     # 如果头像要求是圆形,做一个罩子把四角遮住
  22.     size = (120, 120)
  23.     mask = Image.new('L', size, 0)
  24.     draw = ImageDraw.Draw(mask)
  25.     draw.ellipse((0, 0) + size, fill=255)
  26.     head_cover = ImageOps.fit(head_image, mask.size, centering=(0.5, 0.5))
  27.     head_cover.putalpha(mask)
  28.     # 如果要求是方形,head_cover忽略
  29.     back_image.paste(head_image, (48, 48), head_cover)  # 将头像贴在背景图上
  30.  
  31.     nickname = '程序员罗杰^_^'  # 昵称
  32.     location = (216, 84)  # 昵称位置
  33.     font_color = '#FFFFFF'  # 设置字体颜色
  34.     font_size = 12  # 字体大小
  35.     font_path = './宋体.otf'  # 本地读取的字体文件
  36.     font = ImageFont.truetype(font_path, font_size * 3)
  37.     obj = ImageDraw.Draw(back_image)
  38.     obj.text(location, nickname, font_color, font=font)  # 将昵称贴在背景图上
  39.  
  40.     # 合成二维码
  41.     code_url = ''  # 二维码跳转链接
  42.     qr = qrcode.QRCode(version=3, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=8, border=0)
  43.     qr.add_data(code_url)
  44.     qr.make(fit=True)
  45.     img = qr.make_image()
  46.     qr_code = img.resize((270, 270))  # 设置二维码大小
  47.     qr_location = (48, 1602)  # 二维码位置
  48.     back_image.paste(qr_code, qr_location)  # 将二维码图片贴在背景图上
  49.  
  50.     # 展示成品图
  51.     back_image.show()
  52.     return 'success'
  53.  
  54.  
  55. if __name__ == '__main__':
  56.     gen_poster()