我如何将水印放在图像的中心位置?

时间:2018-07-16 06:51:05

标签: python image automation pillow watermark

我有1万张图像,因此我尝试使用Pillow库在所有图像上添加水印,但是水印位置始终会发生变化,如下图所示。

我想将水印放在每个图像的中心位置,并且水印不应与图像太大和太小,对于每个图像都应该是完美的,所以请您告诉我我该怎么做? / p>

这是水印图像: enter image description here

enter image description here

enter image description here

enter image description here

我正在使用以下代码:

from PIL import Image
import glob


def watermark_with_transparency(input_image_path, output_image_path, watermark_image_path, position):
    base_image = Image.open(input_image_path) #open base image
    watermark = Image.open(watermark_image_path) #open water mark
    width, height = base_image.size #getting size of image

    transparent = Image.new('RGBA', (width, height), (0,0,0,0))
    transparent.paste(base_image, (0,0))
    transparent.paste(watermark, position, mask=watermark)
    #transparent.show()
    transparent.convert('RGB').save(output_image_path)
    print 'Image Done..!'



for inputImage in glob.glob('images/*.jpg'):
    output = inputImage.replace('images\\','')
    outputImage = 'watermark images\\'+str(output)

    watermark_with_transparency(inputImage, outputImage, 'watermark.png', position=(0,0)) #function

2 个答案:

答案 0 :(得分:2)

您将位置传递为0,0。如果要使其居中,则应通过在函数内更新位置,方法是将图像的宽度和高度除以2,然后从中减去水印的宽度和高度除以2。

X coordinate = width_of_image/2 - width_of_watermark/2

Y coordinate = height_of_image/2 - height_of_watermark/2

sample

这是示例代码:

width_of_watermark , height_of_watermark = watermark.size
position = ((width/2-width_of_watermark/2),(height/2-height_of_watermark/2))

答案 1 :(得分:1)

我认为您最好的选择是像这样调整水印的大小:

base_image = Image.open(input_image_path) #open base image
watermark = Image.open(watermark_image_path) #open water mark
watermark = watermark.resize(base_image.size)