生成海报前端-python

7次阅读

共计 2208 个字符,预计需要花费 6 分钟才能阅读完成。

我最近没有摸鱼,一直都在工作。只不过目前需要爬一点数据 python 做的,之后看机会分享一下。

忙着忙着老大说要生成海报,有个活动要给每个用户来个分享图。

想法

  1. PS 批处理?脚本?能甩出去的活都甩出去,机智如我啊
  2. python 处理图像(PIL)。这么坑的想法,当然不是我想的了。虽然我实现了
  3. 写个页面调用之前生成长截图的服务。之前有个为了方便分享微信,做了生成长截图的服务。写个新的页面用一下即可。
  4. 我堂堂前端 er,怎么能一直用别的工具呢?我的锤子呢?

ps 处理

这个方案,经过我调研 行不通 。(也有可能是我菜)
对于批量打码,统一操作这类的还可以。
对于需要对应名字之类的比较无力

python

老大说 pythonpy 使用 PIL 库 写起来还蛮简单的。
py 使用这段时间以来就是感觉这个 编码格式极其难受。有没有大佬解救我一下。

根据不同的类型输出数据

  1. txt 使用字体,输出到对应位置
  2. image 图片,覆盖输出到对应位置。mask=img要注意针对 png 来使用
  3. qrcode 生成对应二维码

通过上面的类型,来增加我们代码的扩展性。

代码

# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
import qrcode
import time;
import re
def AddMoney(data):
  bg = Image.new('RGBA', (data['width'], data['height']))
  for item in data['list']:
    print(item)
    if item['type'] == 'qrcode':
      qr_pil_obj = qrcode.make(item['url'], border=0).resize((item['width'], item['height']), Image.ANTIALIAS)
      bg.paste(qr_pil_obj,(item['x'],item['y']))
    elif item['type'] == 'image':
      extname = re.search(r'(jpg|png|jpeg)$', item['url']).group()
      # 加载图片
      img = Image.open(item['url'])
      # 缩放
      if (item['width']!= ''and item['height'] !=''):
        img.resize((item['width'], item['height']), Image.ANTIALIAS)

      if extname == 'png':
        bg.paste(img,(item['x'],item['y']), mask=img)
      else:
        bg.paste(img,(item['x'],item['y']))
    elif item['type'] == 'text':
      draw = ImageDraw.Draw(bg)
      ttfront = ImageFont.truetype(item['ttfrontUrl'],item['ttfrontSize'])
      draw.text((item['x'],item['y']),unicode(item['txt'],"UTF-8"), fill=(0,0,0), font=ttfront)
    else:
      print('------------------------------')
  bg.save(data['outputName'])

data = {
  'width': 750,
  'height': 1334,
  'outputName': './out-%s.png' % (str(time.time())),
  'list':[{"type":"image","url":"./avatar.jpg","x":10,"y":360,"width":750,"height":1334},{"type":"image","url":"./bg.png","x":0,"y":0,"width":750,"height":750},{"type":"qrcode","url":"https://www.lilnong.top","x":0,"y":0,"width":120,"height":120},{"type":"text","txt":"你这个死宅说话","x":140,"y":560,"ttfrontUrl":"./abc.ttf","ttfrontSize":55},{"type":"text","txt":"还挺搞笑的","x":160,"y":630,"ttfrontUrl":"./abc.ttf","ttfrontSize":55}]
}
AddMoney(data)

长截图

这个也是极好,是之前一个 Node 的服务。省时省力。网上查也不少

前端技术处理

我堂堂前端,怎么也得露一手吧。
基于上面的页面已经成功。我们想一下我们需要干什么?把 html 转成 canvas,然后 canvas.toBlob, 然后 download 美滋滋。

  1. html2canvas 这是一个库,既然已经有写好的了,我们就不费神了。(最难的一步。。。)
  2. 拿到 cavnas 调用 APIcanvas.toBlob
  3. 下载。这个就比较简单了,之前我写过 前端培训 - 初级阶段 - 场景实战(2019-06-06)- 下载文件 & 下载进度

微信公众号

各种忘记发。补上补上

结语

py 写代码是真的短。
前端处理需要注意 跨域 URL 空格 等问题。

正文完
 0