Python給圖像添加水印

圖像水印是一種廣泛使用的技術,允許內容創作者、攝影師和藝術家保護他們的作品並維護他們的所有權。通過將可見標記(通常以徽標或文本的形式)應用到圖像上,水印可以阻止未經授權的使用和版權侵權。在本文中,我們將為您提供一個簡單而有效的解決方案,在 Python 中為圖像添加水印。那麼讓我們看看如何做。

為圖像添加水印的 Python 庫

Aspose.Imaging for Python 是一個功能強大的圖像處理庫,可處理多種圖像格式。無需編寫複雜的代碼,該庫即可讓您輕鬆處理圖像。您可以下載該庫或使用以下命令安裝它。

> pip install aspose-imaging-python-net 

使用 Python 向圖像添加水印

Aspose.Imaging for Python 使得在圖像上插入水印變得非常簡單,只需幾行代碼即可完成。以下是在 Python 中為圖像添加水印的步驟。

  • 使用 Image 類加載圖像。
  • 創建 Graphics 類的實例並使用 Image 對像對其進行初始化。
  • 使用 Font 類設置字體系列、大小和外觀。
  • 創建 SolidBrush 類的實例並設置其屬性,例如顏色等。
  • 實例化 StringFormat 類以設置文本對齊方式。
  • 使用 Graphics.drawstring(String, Font, SolidBrush, 0, 0, StringFormat) 方法向圖像添加水印。
  • 使用 Image.save(String) 方法保存圖像。

以下代碼示例展示瞭如何使用 Python 向圖像添加水印。

import aspose.pycore as aspycore
from aspose.imaging import *
from aspose.imaging.brushes import *
from aspose.imaging.fileformats.jpeg import *
from aspose.pycore import as_of, is_assignable
import os

if 'TEMPLATE_DIR' in os.environ:
	templates_folder = os.environ['TEMPLATE_DIR']
else:
	templates_folder = r"C:\Users\USER\Downloads\templates"

delete_output = 'SAVE_OUTPUT' not in os.environ

data_dir = templates_folder

# 加載圖片
with Image.load(os.path.join(data_dir, "template.tiff")) as image:
	# 水印文字
	the_string = "45 Degree Rotated Text"
	graphics = Graphics(image)
	sz = graphics.image.size
	
	# 設置字體
	font = Font("Times New Roman", 20.0, FontStyle.BOLD)
	brush = SolidBrush()
	brush.color = Color.red
	brush.opacity = 0
	format_ = StringFormat()
	format_.alignment = StringAlignment.CENTER
	format_.format_flags = StringFormatFlags.MEASURE_TRAILING_SPACES
	matrix = Matrix()
	matrix.translate(sz.width / 2, sz.height / 2)
	
	# 設置旋轉角度
	matrix.rotate(-45.0)
	graphics.transform = matrix
	
	# 應用水印
	graphics.draw_string(the_string, font, brush, 0, 0, format_)
	
	# 保存圖片
	image.save(os.path.join(data_dir, "result.jpg"))

if delete_output:
	os.remove(os.path.join(data_dir, "result.jpg"))

下面是使用上面的代碼示例添加到圖像的水印。

向圖像Python添加對角線水印

在線水印圖像

使用我們的免費在線圖像水印工具 在您需要的任意數量的圖像上添加水印。您無需創建帳戶即可使用此工具。

免費的 Python 圖像水印庫

您可以獲取免費的臨時許可證並在圖像上插入水印,而不受評估限制。

結論

在本文中,您學習瞭如何在 Python 中為圖像添加水印。分步指南和代碼示例演示瞭如何在具有特定設置的圖像上應用水印。此外,我們還為您提供了在圖像上插入水印的在線工具。這是一個免費工具,您無需創建任何帳戶即可使用它。

如果您想了解有關我們的 Python 圖像處理庫的更多信息,請訪問文檔。如果您有任何問題或疑問,請通過我們的論壇與我們聯繫。

也可以看看