Python Pillow - 新增影像邊框



在影像處理中,新增影像邊框是一項常見的任務。邊框可以幫助框定內容,吸引對特定區域的注意,或新增裝飾元素。在 Pillow (PIL) 中,使用 **ImageOps** 模組的 **expand()** 方法可以增加影像的尺寸,在影像周圍新增邊框或填充。這對於新增邊框、建立特定尺寸的畫布或調整影像大小以適應特定縱橫比等多種用途都很有幫助。

expand() 方法

**expand()** 方法可用於為影像新增邊框並調整其尺寸,同時保持縱橫比。我們可以自定義大小和邊框顏色以滿足我們的特定需求。

以下是 expand() 方法的基本語法:

PIL.Image.expand(size, fill=None)

其中:

  • **size** - 指定擴充套件影像的新尺寸(即寬度和高度)的元組。

  • **fill (可選)** - 用於填充邊框區域的可選顏色值。它應指定為顏色元組 (R, G, B) 或表示顏色的整數值。

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

expanded image

示例

在這個示例中,我們使用 **expand()** 方法建立帶有邊框的擴充套件影像。

from PIL import Image, ImageOps

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

#Define the new dimensions for the expanded image
new_width = image.width + 40  
#Add 40 pixels to the width
new_height = image.height + 40  
#Add 40 pixels to the height

#Expand the image with a white border
expanded_image = ImageOps.expand(image, border=20, fill="red")

#Save or display the expanded image
expanded_image.save("output Image/expanded_output.jpg")
open_expand = Image.open("output Image/expanded_output.jpg")
open_expand.show()

輸出

image with red border

示例

這是另一個示例,我們使用 **Image** 模組的 **expand()** 方法使用藍色擴充套件影像邊框。

from PIL import Image, ImageOps

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

#Define the new dimensions for the expanded image
new_width = image.width + 40  
#Add 40 pixels to the width
new_height = image.height + 40  
#Add 40 pixels to the height

#Expand the image with a white border
expanded_image = ImageOps.expand(image, border=100, fill="blue")

#Save or display the expanded image
expanded_image.save("output Image/expanded_output.jpg")
open_expand = Image.open("output Image/expanded_output.jpg")
open_expand.show()

輸出

image with blue border
廣告