這個是個比較常見的需求,好比你在某個網站上發佈了圖片,在圖片上就會出現帶你暱稱的水印。那麼在Python中應該如何處理這一類需求呢?html
其實在個人《Django實戰開發》視頻教程中有講到這一部分,Django結合了xadmin,再集成進來 django-ckeditor以後,有了比較方便的富文本編輯器了,對於圖片也就須要增長一個水印的功能。這裏把其中的代碼抽一部分出來,僅供參考。django
須要先安裝Pillow: pip install pillow
app
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)
馬蜂窩遊記推廣 蜘蛛池程序下載安裝 http://mseo.chinaz.com/asdasdasd.nx04.com/ http://seo.chinaz.com/sdfasd.nx04.com/網站