Python Pillow - 在影像上寫入文字



向影像新增文字是一項常見的影像處理任務,它涉及將文字疊加到影像上。這可以用於各種目的,例如為影像新增標題、標籤、水印或註釋。在向影像新增文字時,我們通常可以指定文字內容、字型、大小、顏色和位置。

在 Pillow (PIL) 中,我們可以使用 **ImageDraw** 模組中的 **text()** 方法向影像新增文字。

text() 方法

**text()** 方法允許我們指定要新增文字的位置、文字內容、字型和顏色。

語法

以下是使用 **text()** 方法的基本語法和引數:

PIL.ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left")
  • **xy** - 文字應放置的位置。它應該是一個元組 '(x, y)',表示座標。

  • **text** - 我們想要新增到影像的文字內容。

  • **fill (可選)** - 文字的顏色。它可以指定為 RGB 顏色的元組 '(R, G, B)',灰度顏色的單個整數,或命名顏色。

  • **font (可選)** - 用於文字的字型。我們可以使用 'ImageFont.truetype()' 或 'ImageFont.load()' 指定字型。

  • **anchor (可選)** - 指定文字應如何錨定。選項包括“left”、“center”、“right”、“top”、“middle”和“bottom”。

  • **spacing (可選)** - 指定文字行之間的間距。使用正值增加間距,或使用負值減少間距。

  • **align (可選)** - 指定文字在邊界框內的水平對齊方式。選項包括“left”、“center”和“right”。

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

book

示例

在這個示例中,我們使用 **Image** 模組的 **text()** 方法將文字 **Tutorialspoint** 新增到輸入影像中。

from PIL import Image, ImageDraw, ImageFont

#Open an image
image = Image.open("Images/book.jpg")

#Create a drawing object
draw = ImageDraw.Draw(image)

#Define text attributes
text = "Tutorialspoint"
font = ImageFont.truetype("arial.ttf", size=30)
text_color = (255, 0, 0)  
#Red
position = (50, 50)

#Add text to the image
draw.text(position, text, fill=text_color, font=font)

#Save or display the image with the added text
image.save("output Image/textoutput.jpg")
opentext = Image.open("output Image/textoutput.jpg")
opentext.show()

輸出

textoutput

示例

這是另一個使用 **ImageDraw** 模組的 **text()** 方法向影像新增文字的示例。

from PIL import Image, ImageDraw, ImageFont

#Open an image
image = Image.open("Images/book.jpg")

#Create a drawing object
draw = ImageDraw.Draw(image)

#Define text attributes
text = "Have a Happy learning"
font = ImageFont.truetype("arial.ttf", size=10)
text_color = (255, 0, 255)  
position = (150, 100)

#Add text to the image
draw.text(position, text, fill=text_color, font=font)

#Save or display the image with the added text
image.save("output Image/textoutput.jpg")
opentext = Image.open("output Image/textoutput.jpg")
opentext.show()

輸出

textoutput
廣告