【问题标题】:How to create PNG templates with Python如何使用 Python 创建 PNG 模板
【发布时间】:2021-01-28 21:59:57
【问题描述】:

我将如何创建可以传递数据或信息的 PNG 模板,以便它显示在图像中?为了澄清起见,我正在考虑类似于GitHub README Stats 的工作方式,但使用的是 PNG 而不是 SVG。或者小部件如何用于 Discord 的小部件图像(例如 https://discordapp.com/api/guilds/guildID/widget.png?style=banner1)。

如果没有这类东西的库,那么制作一个库需要什么? (我需要消磨时间,所以我非常热衷于制作一些东西,即使它只适合我的需要)。

【问题讨论】:

    标签: python image templates


    【解决方案1】:

    您可以使用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 是一个图像处理库,它可以像 GIMP 一样使用 Python 编辑图像(但它更有限)。

    在这段代码中,我们声明了一个名为myTemplate的类,这将是我们的模板,在这个类中我们有两个函数,一个将初始化该类,并请求namedescriptionimage,以及另一个会画。

    好吧,从1315 行,程序导入并验证是否有选定的图像,如果有,它会裁剪并调整选定图像的大小(1617),然后粘贴选定的图像模板中的图像。

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

    您可以根据需要自定义课程和26

    图片参考

    模板.png

    images.jfif

    out.png

    【讨论】:

    • 谢谢你,解释和代码示例正是我所需要的。
    猜你喜欢
    • 2018-01-18
    • 2020-11-09
    • 1970-01-01
    • 2020-04-04
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2012-01-12
    相关资源
    最近更新 更多