Python Pillow 简明教程

Python Pillow - Creating a Watermark

What is Watermark?

watermark 是可识别的且常见的透明图像或文字,其叠加在其他图像、文档或对象上,表明其所有权、作者或来源。水印通常用于保护知识产权和内容,防止其未经授权使用或分发,并提供归属。它们有以下所述的各种用途 −

  1. Copyright Protection − 艺术家、摄影师和内容创作者经常使用水印来通过用其姓名、徽标或版权信息标记他们的作品来保护其知识产权。这有助于阻止未经授权使用或分发其内容。

  2. Branding − 公司和组织使用水印通过用其徽标、名称或标语为其图像或文档冠名。这强化了其品牌标识,并清楚表明内容的来源。

  3. Document Verification − 水印可用于官方文件,例如证书上,以防止伪造或未经授权的复制。例如,毕业证书或公证文件可能有水印。

  4. Security − 在货币和其他安全文件中,复杂的且通常不可见的水印用于阻止伪造。这些水印难以准确复制,从而更容易检测伪造的钞票或文件。

  5. Image Attribution − 在股票摄影和图像许可的上下文中,水印可用于显示带水印的图像预览。当用户购买图像时,他们会收到不带水印的版本。

  6. Digital Media − 在数字世界中,水印经常用于在线共享的图像和视频中,以保护内容。它们也可以用来给原始创建者授予表彰。

水印可以采用各种形式,例如文本、徽标、模式,甚至嵌入内容中的不可见数据。在放置时,绝大多数情况下不会损失内容的质量,其目的是提供真实性或所有权的可视或数字指示器。

Creating the text watermark

现在让我们探讨如何使用 pillow 库创建文字水印。在 pillow 中,没有直接创建水印的方法,但我们可以使用 ImageDraw, ImageFontImage 方法来实现。

以下是本章所有示例中使用的输入图像。

butterfly original image

Example

在此示例中,我们使用 pillow 库创建文本 Tutorialspoint 作为水印。

from PIL import Image, ImageDraw, ImageFont
original_image = Image.open("Images/butterfly.jpg")
draw = ImageDraw.Draw(original_image)
watermark_text = "Tutorialspoint"
font_size = 20
font = ImageFont.truetype("arial.ttf", font_size)
text_color = (255, 255, 255)

#White color (RGB)
text_width, text_height = draw.textsize(watermark_text, font)
image_width, image_height = original_image.size
margin = 10

#Margin from the right and bottom edges
position = (image_width - text_width - margin, image_height - text_height - margin)
draw.text(position, watermark_text, font=font, fill=text_color)
original_image.save("output Image/watermarked_image.png")
original_image.show()
watermarked

Creating the image Watermark

之前我们在图像上创建了文字水印,同样,我们可以使用 pillow 中提供的 ImageDraw, copypaste 方法创建一个图像作为水印。

Example

在此示例中,我们通过 pillow 中提供的 Tutoriaslpoint 方法创建徽标图像作为水印。

from PIL import Image
original_image = Image.open("Images/butterfly.jpg")
watermark = Image.open("Images/tutorialspoint.png")
#Use the appropriate image file for your watermark

#Resize the watermark image to a specific width or height
target_width = 200

#Adjust this to our preferred size
aspect_ratio = float(target_width) / watermark.width
target_height = int(watermark.height * aspect_ratio)
watermark = watermark.resize((target_width, target_height), Image.ANTIALIAS)
watermarked_image = original_image.copy()

#Adjust the position where you want to place the watermark (e.g., bottom right corner)
position = (original_image.width - watermark.width, original_image.height - watermark.height)
watermarked_image.paste(watermark, position, watermark)
watermarked_image.save("output Image/watermarked_image.jpg")
watermarked_image.show()
watermarked tp