python库pillow:实现生成图片并加水印 一、背景 二、实现 三、预览

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

二、实现

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

 1 def generate_image(static_dir, image_type, width, height, color):
 2     print(static_dir, image_type, width, height, color)
 3 
 4     mode = 'RGB'
 5     width = int(width)
 6     height = int(height)
 7     color_tuple = ImageColor.getcolor(color, mode)
 8 
 9     image = Image.new(mode, (width, height), color_tuple)
10 
11     image_dir = os.path.join(static_dir, 'image')
12     image_name = '%sx%s_%s.%s' % (width, height, int(time.time()), image_type)
13     image_path = os.path.join(image_dir, image_name)
14 
15     font = ImageFont.truetype('./font/consola.ttf', 96)
16     draw = ImageDraw.Draw(image)
17     mark_content = '{width}x{height}'.format(width=width, height=height)
18     for i, ch in enumerate(mark_content):
19         draw.text((60*i + 10, 10), ch, font=font, fill=rndColor())
20 
21     image.save(image_path)
22 
23     print('image_path:%s' % (image_path))
24     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