基于PIL库生成图文组合的图片

废话不多说,现学现卖

# _*_ coding:utf-8 _*_

from PIL import Image, ImageDraw, ImageFont
import os


class SaveImage:

    def __init__(self, codePath, text, fontSize, savePath, filename,
                 fontPath='C:\Windows\Fonts\msyh.ttc'):
        self.codePath = codePath
        self.text = text
        self.fontPath = fontPath
        self.fontSize = fontSize
        self.savePath = savePath
        self.filename = filename

    def sago(self):
        code = Image.open(self.codePath)
        weidth, height = code.size
        font = ImageFont.truetype(self.fontPath, self.fontSize)
        # an new background image
        bgImage = Image.new('RGB', (weidth, height * 2), color=(255, 255, 255))
        bgImage.paste(code, box=(0, 0))
        draw = ImageDraw.Draw(bgImage)
        if '\n' in self.text:
            draw.multiline_text((25, height + 20), self.text, (0, 0, 0), font=font)
        else:
            draw.text((25, height + 20), self.text, (0, 0, 0), font=font)
        if not os.path.exists(self.savePath):
            os.makedirs(self.savePath)
        bgImage.save(self.savePath + self.filename)
        return self.savePath

另外, 基于前端开发,生成图文组合的图片, 可以使用  html2canvas.js

<script src="js/jquery.min.js"></script>
<script src="js/html2canvas.js"></script>

<script>

function save_png() {
            var code = $('#details').attr('cod');
            html2canvas($('#printarea'), {
                onrendered: function (canvas) {
                    getCanvas = canvas;
                },
                background:'white',
                allowTaint: true,
                borderStyle: 'solid',
                fontWeight: 10,
            });
            var imageData = getCanvas.toDataURL("image\/png");
            var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
            $('#save').attr("download", "" + code + ".png").attr('href', newData);
        }

</script>

生成条形码图片(pip install pystrich)

import os
from pystrich.ean13 import EAN13Encoder
from pystrich.code128 import Code128Encoder
def save_bar_code(short_code, file_path='static/image/', font_path='/usr/share/fonts/msyh/msyh.ttc'):
    encoder = Code128Encoder(short_code,
                             options={'label_border': 1, 'bottom_border': 2, 'ttf_font':font_path ,
                                      'ttf_fontsize': 13})
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    image_path = file_path + short_code + '.png'
    encoder.save(image_path)
    return image_path

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

莱斯笔记

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

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

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

打赏作者

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

抵扣说明:

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

余额充值