Python基于pillow库实现生成图片水印

一、背景

平时工作中经常需要使用各种尺寸、格式的图片来做测试,每次从百度或者谷歌找图都非常麻烦,于是就想作为一个程序员怎么能被这个问题影响效率呢,一切程序可以做的事情都应该用程勋来做并提升效率,这才是我们编程的意义所在。

二、实现

于是就想实现一个web版的图片生成器,填颜色、尺寸、格式就可以生成指定的图片,Python的图像库肯定首选pillow,实现起来很简单,所以就不详细解释了,直接上代码:

def generate_image(static_dir, image_type, width, height, color):
  print(static_dir, image_type, width, height, color)

  mode = 'RGB'
  width = int(width)
  height = int(height)
  color_tuple = ImageColor.getcolor(color, mode)

  image = Image.new(mode, (width, height), color_tuple)

  image_dir = os.path.join(static_dir, 'image')
  image_name = '%sx%s_%s.%s' % (width, height, int(time.time()), image_type)
  image_path = os.path.join(image_dir, image_name)

  font = ImageFont.truetype('./font/consola.ttf', 96)
  draw = ImageDraw.Draw(image)
  mark_content = '{width}x{height}'.format(width=width, height=height)
  for i, ch in enumerate(mark_content):
    draw.text((60*i + 10, 10), ch, font=font, fill=rndColor())

  image.save(image_path)

  print('image_path:%s' % (image_path))
  return image_path

这个就是核心的生成图片的逻辑,其中稍微费了点时间的是水印的生成,这里添加水印的用意是为了在图片上显示图片的尺寸,方便使用者直观的看到该图片的尺寸,其中需要使用到ImageDraw.text()方法,这里需要注意的是要根据你的字体大小设置合适的字间距,我是通过多次调整尝试的,最终得到一个自己满意的效果。

另外,关于字体名字,默认在不同平台下会去不同的目录查找该名字的字体,Windows下是在c://windows/fonts/目录下,Linux是在/usr/share/fonts目录下,这里为了避免后续部署时不同电脑上字体不同导致的问题,我直接把字体文件放在代码库中了,所以使用的是一个相对路径。

三、预览

如果想要预览效果的,可以访问这里:https://nicolerobin.top/image_holder/static/index.html

代码库地址:https://github.com/NicoleRobin/image_holder

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。