本帖最后由 唐伯虎(0) 于 2019-2-14 13:55 编辑
from PIL import Image, ImageDraw, ImageFont
import sys
def watermark_with(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_with(f, '水印', 'red')
with open('new_image_water.png', 'wb') as f:
image_with.save(f)
|
|