使用python自动化png格式
发布时间:2020-12-20 13:48:33 所属栏目:Python 来源:网络整理
导读:我正试图找到一种方法来自动格式化png以添加标题字幕和带有徽标图像和来源的页脚栏.我想用 python做这个图像格式化,因为我最熟悉那种语言.我在这里寻找一些方向,哪些模块可以用于这样的东西?理想情况下,对于脚本用户来说,该过程看起来像这样. 1)用户将有一
我正试图找到一种方法来自动格式化png以添加标题字幕和带有徽标图像和来源的页脚栏.我想用
python做这个图像格式化,因为我最熟悉那种语言.我在这里寻找一些方向,哪些模块可以用于这样的东西?理想情况下,对于脚本用户来说,该过程看起来像这样.
1)用户将有一个看起来像这样的png图像: 2)用户将启动脚本: python autochart_formatting.py 3)脚本会提示用户输入以下信息: >输入图表标题: 3)使用该信息,png将被格式化为看起来像这样: 解决方法
Pillow (the maintained successor to PIL: Python Imaging Library)可以准确处理您想要的内容.
您可以在检索用户输入后扩展图像并放置文本.以下是添加标题的示例: from PIL import Image,ImageFont,ImageDraw img = Image.open('my_chart.png') w,h= img.size # put pixels into 2D array for ease of use data = list(img.getdata()) xy_data = [] for y in xrange(h): temp = [] for x in xrange(w): temp.append(data[y*w + x]) xy_data.append(temp) # get the title title = raw_input("Title:") # load the font font_size = 20 font = ImageFont.truetype("/path/to/font.ttf",font_size) # Get the required height for you images height_needed = font.getsize(title)[1] + 2 # 2 px for padding # get the upperleft pixel to match color bg = xy_data[0][0] # add rows to the data to prepare for the text xy_data = [[bg]*w for i in range(height_needed+5)] + xy_data # +5 for more padding # resize image img = img.resize((w,h+height_needed+5)) # convert data back to 1D array data = [] for line in xy_data: data += line # put the image back in the data img.putdata(data) # get the ImageDraw item for this image draw = ImageDraw.Draw(img) # draw the text draw.text((5,0),title,font=font,fill=(0,0)) # fill is black img.save('titled_plot.png') (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |