這個是個比較常見的需求,比如你在某個網站上發佈了圖片,在圖片上就會出現帶你暱稱的水印。那麼在Python中應該如何處理這一類需求呢?
其實在我的《Django實戰開發》視頻教程中有講到這一部分,Django結合了xadmin,再集成進來 django-ckeditor之後,有了比較方便的富文本編輯器了,對於圖片也就需要增加一個水印的功能。這裏把其中的代碼抽一部分出來,僅供參考。
需要先安裝Pillow: pip install pillow
Demo代碼:
import sys
from PIL import Image, ImageDraw, ImageFont
def watermark_with_text(file_obj, text, color, fontfamily=None):
image = Image.open(file_obj).convert('RGBA')
draw = ImageDraw.Draw(image)
width, height = image.size
margin = 10
if fontfamily:
font = ImageFont.truetype(fontfamily, int(height / 20))
else:
font = None
textWidth, textHeight = draw.textsize(text, font)
x = (width - textWidth - margin) / 2 # 計算橫軸位置
y = height - textHeight - margin # 計算縱軸位置
draw.text((x, y), text, color, font)
return image
if __name__ == '__main__':
org_file = sys.argv[1]
with open(org_file, 'rb') as f:
image_with_watermark = watermark_with_text(f, 'the5fire.com', 'red')
with open('new_image_water.png', 'wb') as f:
image_with_watermark.save(f)
使用方法:
python watermart.py <圖片地址>
這個只是把文本嵌入到圖片中的實現,其實也可以嵌入一個圖片進去的。具體可以參考:
https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.alpha_composite
相關文章: