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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
