用python3根据配置自动生成自定义图片logo(一键解决图片侵权困扰)

欢迎关注原创视频教程

Python微信订餐小程序课程视频

https://edu.csdn.net/course/detail/36074

Python实战量化交易理财系统

https://edu.csdn.net/course/detail/35475
python3开发了一个小工具,可根据配置文件生成想要的图片,这只是一个雏形,我的想法是把这个脚本融入到h3blog博客系统当中,真正意义上解决博客系统图源的问题。话不不说直接看代码。

程序执行

import re
from io import BytesIO
import requests
from PIL import Image,ImageDraw,ImageFont
import os

class H3blogDrow:
    '''自定义图片样式'''
    def __init__(self) -> None:
        self.width = 800
        self.heigth = 400
        self.background_img = ''
        self.background_color = (42, 41, 55)
        self.layers = []
        self.convas = None

    def parse_config(self, config: dict) -> None:
        c = config
        self.convas = None
        self.width = c.get('width', 800)
        self.heigth = c.get('height', 400)
        self.background_color = tuple([int(i) for i in c.get('background_color', '').split(',')])
        self.background_img = c.get('background_img', (42, 41, 55))

        layers = c.get('layers', None)
        if not layers:
            return
        self.layers.extend(layers)

    def _create_canvas(self) -> None:
        self.convas = Image.new('RGB', (self.width, self.heigth), self.background_color)


    def draw(self) -> Image:
        '''画图'''
        # 创建背景设置画布
        self._create_canvas()

        if self.background_img and len(self.background_img) > 0:
            regex = re.compile(
                r'^(?:http|ftp)s?://' # http:// or https://
                r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
                r'localhost|' #localhost...
                r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
                r'(?::\d+)?' # optional port
                r'(?:/?|[/?]\S+)$', re.IGNORECASE)
            m = re.match(regex, self.background_img)
            bg_img = None
            if m :
                resp = requests.get(self.background_img)
                _img_bytes = BytesIO()
                _img_bytes.write(resp.content)
                bg_img = Image.open(_img_bytes)
            else:
                #创建背景图片
                bg_img = Image.open(self.background_img)
            #将背景图片写入画布
            self.convas.paste(bg_img, (0,0))

        for layer in self.layers:
            if layer.get('layer_type') == 'text':
                self._draw_text(layer)
            if layer.get('layer_type') == 'image':
                self._draw_image()

        return self.convas

    def _darw_image(self, layer: dict) -> None:
        pass

    def _draw_text(self, layer: dict) -> None:
        draw = ImageDraw.Draw(self.convas)
        _font = layer.get('font')
        font = ImageFont.truetype(_font.get('font'), _font.get('size', 36))
        align = layer.get('align')
        p = tuple()
        if align and align == 'center':
            f_w, f_h = font.getsize(layer.get('text')) #获取字体大小
            p = ((self.convas.width - f_w)/2, (self.convas.height - f_h)/2)
        elif align and align == 'top-left':
            p = (0,0)
        elif align and align == 'top-right':
            f_w, f_h = font.getsize(layer.get('text')) #获取字体大小
            p = (self.convas.width - f_w, 0)
        elif align and align == 'bottom-left':
            f_w, f_h = font.getsize(layer.get('text')) #获取字体大小
            p = (0, self.convas.height - f_h)
        elif align and align == 'bottom-right':
            f_w, f_h = font.getsize(layer.get('text')) #获取字体大小
            p = (self.convas.width - f_w, self.convas.height - f_w)
        else:
            p = tuple([int(i) for i in layer.get('position','0,0').split(',')])
        color = tuple([int(i) for i in layer.get('color','0,0,0').split(',')])
        draw.text(p, layer.get('text',''), fill = color, font = font)


module_path = os.path.dirname(__file__)
config = {
    'width': 400,
    'height': 400,
    'background_img': 'https://pics2.baidu.com/feed/42166d224f4a20a4eabad448d020e92b730ed011.jpeg?token=fb826ebd6b5e1ca8e1fe009f7dab5735',
    'background_color':'42,41,55',

    'layers': [
        {
            'layer_type': 'text',
            'color': '255,0,0',
            'font': {
                'font': module_path + '\\站酷庆科黄油体.ttf',
                'size': 60,
            },
            'position': '0,100',
            'align': 'center',
            'text': '来都来'
        },
        {
            'layer_type': 'text',
            'color': '255,255,255',
            'font': {
                'font': module_path + '\\站酷庆科黄油体.ttf',
                'size': 60,
            },
            'position': '',
            'align': 'top-left',
            'text': '左上'
        },
        {
            'layer_type': 'text',
            'color': '0,255,0',
            'font': {
                'font': module_path + '\\站酷庆科黄油体.ttf',
                'size': 60,
            },
            'position': '',
            'align': 'top-right',
            'text': '右上'
        },
        {
            'layer_type': 'text',
            'color': '0,0,255',
            'font': {
                'font': module_path + '\\站酷庆科黄油体.ttf',
                'size': 60,
            },
            'position': '',
            'align': 'bottom-left',
            'text': '左下'
        },
        {
            'layer_type': 'text',
            'color': '155,0,255',
            'font': {
                'font': module_path + '\\站酷庆科黄油体.ttf',
                'size': 60,
            },
            'position': '',
            'align': 'bottom-right',
            'text': '右下'
        },
    ],
}


d = H3blogDrow()
d.parse_config(config)
img = d.draw()
#img.show()
filename = module_path + '\\image_save_20210509.jpg'
#img.save("C:\\Users\\Administrator\\Desktop\\xlspy\\image_save_20200509.jpg")
img.save(filename)

最终结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虚坏叔叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值