Python 中使用 Pillow 處理圖片增加水印,保護你的圖片版權
阿新 • • 發佈:2020-12-02
本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯絡我們以作處理
以下文章來源於騰訊雲 作者:the5fire
( 想要學習Python?Python學習交流群:1039649593,滿足你的需求,資料都已經上傳群檔案流,可以自行下載!還有海量最新2020python學習資料。 )
這個是個比較常見的需求,比如你在某個網站上釋出了圖片,在圖片上就會出現帶你暱稱的水印。那麼在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 <圖片地址>