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
您可能感兴趣的文章您可能感兴趣的文章:Python图片处理模块PIL操作方法(pillow)python3使用Pillow、tesseract-ocr与pytesseract模块的图片
识别的方法Python Pillow.Image 图像保存和参数选择方式Python 3 使用Pillow生成漂亮的分形树图片Python 使用 Pillow 模块
给图片添加文字水印的方法python pillow模块使用方法详解详解python3安装pillow后报错没有pillow模块以及没有PIL模块问题
解决Python3安装Pillow与PIL的方法
评论0
最新资源