fri*_*syn 4 python templates image
我将如何创建可以传递数据或信息的 PNG 模板,以便它显示在图像中?为了澄清起见,我正在考虑类似于GitHub README Stats工作方式的东西,但使用 PNG 而不是 SVG。或者小部件如何适用于 Discord 的小部件图像(例如https://discordapp.com/api/guilds/guildID/widget.png?style=banner1)。
如果没有此类东西的库,需要什么才能制作一个呢?(我需要一个时间沉淀器,所以我非常热衷于制作一些东西,即使它只适合我的需要)。
小智 5
你可以使用PIL
from PIL import Image, ImageDraw, ImageFont #Import PIL functions
class myTemplate(): #Your template
def __init__(self, name, description, image):
self.name=name #Saves Name input as a self object
self.description=description #Saves Description input as a self object
self.image=image #Saves Image input as a self object
def draw(self):
"""
Draw Function
------------------
Draws the template
"""
img = Image.open(r'C:\foo\...\template.png', 'r').convert('RGB') #Opens Template Image
if self.image != '':
pasted = Image.open(self.image).convert("RGBA") #Opens Selected Image
pasted=pasted.resize((278, int(pasted.size[1]*(278/pasted.size[0])))) #Resize image to width fit black area's width
pasted=pasted.crop((0, 0, 278, 322)) #Crop height
img.paste(pasted, (31, 141)) #Pastes image into template
imgdraw=ImageDraw.Draw(img) #Create a canvas
font=ImageFont.truetype("C:/Windows/Fonts/Calibril.ttf", 48) #Loads font
imgdraw.text((515,152), self.name, (0,0,0), font=font) #Draws name
imgdraw.text((654,231), self.description, (0,0,0), font=font) #Draws description
img.save(r'C:\foo\...\out.png') #Saves output
amaztemp=myTemplate('Hello, world!', 'Hi there', r'C:\foo\...\images.jfif')
amaztemp.draw()
Run Code Online (Sandbox Code Playgroud)
PIL 是一个图像操作库,它可以像 GIMP 一样用 Python 编辑图像(但其局限性更大)。
在这段代码中,我们声明一个名为 的类myTemplate,它将作为我们的模板,在这个类中我们有两个函数,一个将初始化该类,然后 requestname和description,image另一个将绘制。
好吧,从第 到13行15,程序导入并验证是否存在选定的图像,如果是,则裁剪选定的图像并调整其大小(16和17),然后将选定的图像粘贴到模板中。
之后,绘制名称和描述,然后程序保存文件。
26您可以根据需要定制课程和线路