Python批量生成特定尺寸图片及图画任意文字的实例

yipeiwu_com5年前Python基础

因为工作需要生成各种大小的图片,所以写了个小脚本,顺便支持了下图画文字内容。

具体代码如下:

from PIL import Image, ImageDraw, ImageFont
'''
  Auth: Xiaowu Chen
  Note: Please install [pillow] library before run this script.
'''
 
 
def draw_image(new_img, text, show_image=False):
  text = str(text)
  draw = ImageDraw.Draw(new_img)
  img_size = new_img.size
  draw.line((0, 0) + img_size, fill=128)
  draw.line((0, img_size[1], img_size[0], 0), fill=128)
 
  font_size = 40
  fnt = ImageFont.truetype('arial.ttf', font_size)
  fnt_size = fnt.getsize(text)
  while fnt_size[0] > img_size[0] or fnt_size[0] > img_size[0]:
    font_size -= 5
    fnt = ImageFont.truetype('arial.ttf', font_size)
    fnt_size = fnt.getsize(text)
 
  x = (img_size[0] - fnt_size[0]) / 2
  y = (img_size[1] - fnt_size[1]) / 2
  draw.text((x, y), text, font=fnt, fill=(255, 0, 0))
 
  if show_image:
    new_img.show()
  del draw
 
 
def new_image(width, height, text='default', color=(100, 100, 100, 255), show_image=False):
  new_img = Image.new('RGBA', (int(width), int(height)), color)
  draw_image(new_img, text, show_image)
  new_img.save(r'%s_%s_%s.png' % (width, height, text))
  del new_img
 
 
def new_image_with_file(fn):
  with open(fn, encoding='utf-8') as f:
    for l in f:
      l = l.strip()
      if l:
        ls = l.split(',')
        if '#' == l[0] or len(ls) < 2:
          continue
 
        new_image(*ls)
 
 
if '__main__' == __name__:
  new_image(400, 300, 'hello world any size', show_image=True)
  # new_image_with_file('image_data.txt')
 
 

如果你需要批量的话,批量数据文件的格式如下:

#width,height,text
200,200,hello
300,255,world

执行后的效果如下:

Python批量生成特定尺寸图片及图画任意文字

以上这篇Python批量生成特定尺寸图片及图画任意文字的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python分支结构(switch)操作简介

Python当中并无switch语句,本文研究的主要是通过字典实现switch语句的功能,具体如下。 switch语句用于编写多分支结构的程序,类似与if….elif….else语句。...

Flask框架实现的前端RSA加密与后端Python解密功能详解

Flask框架实现的前端RSA加密与后端Python解密功能详解

本文实例讲述了Flask框架实现的前端RSA加密与后端Python解密功能。分享给大家供大家参考,具体如下: 前言 在使用 Flask 开发用户登录API的时候,我之前都是明文传输 us...

Sanic框架请求与响应实例分析

本文实例讲述了Sanic框架请求与响应。分享给大家供大家参考,具体如下: 前面介绍了Sanic框架的路由,这里接着介绍Sanic框架的请求与响应。 简介 Sanic是一个类似Flask的...

python下setuptools的安装详解及No module named setuptools的解决方法

前言 python下的setuptools带有一个easy_install的工具,在安装python的每三方模块、工具时很有用,也很方便。 安装setuptools前先安装pip,请参...

Flask框架重定向,错误显示,Responses响应及Sessions会话操作示例

本文实例讲述了Flask框架重定向,错误显示,Responses响应及Sessions会话操作。分享给大家供大家参考,具体如下: 重定向和错误显示 将用户重定向到另一个端点,使用redi...