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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM