废话不多说,现学现卖
# _*_ 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