如何利用Python创建PNG模板

4
我该如何创建 PNG 模板并传递数据或信息以便在图像中显示?为了澄清,我想的是类似于 GitHub README Stats 的东西,但是使用 PNG 而不是 SVG。或者类似于 Discord Widget 图像的小部件的工作方式(例如:https://discordapp.com/api/guilds/guildID/widget.png?style=banner1)。如果没有适合这种情况的库,那么制作一个需要什么?(我需要消磨时间,所以即使只符合我的需求,我也很有兴趣制作某些东西。)
1个回答

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()

说明

PIL是一种图像处理库,它可以像Python中的GIMP一样编辑图像(但其功能更加有限)。

在这段代码中,我们声明了一个名为myTemplate的类,它将作为我们的模板,类内部有两个函数,一个将初始化该类,并请求namedescriptionimage,另一个将进行绘制。

好的,从第13行到第15行,程序导入并验证是否存在选定的图像,如果有,则裁剪和调整所选图像(第1617行),然后将所选图像粘贴到模板中。

此后,会绘制名称和描述,然后程序保存文件。

您可以根据自己的需求自定义类和第26行。

图像参考

template.png

template.png

images.jfif

images.jfif

out.png

out.png


1
谢谢,你的解释和代码示例正是我所需要的。 - frissyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接