Python Pillow - 使用顏色建立影像



什麼是使用顏色建立影像?

在 Pillow(Python Imaging Library,現在稱為 Pillow)中使用顏色建立影像,涉及建立填充特定顏色的新影像。在 Pillow 中使用顏色建立影像,需要生成特定大小的影像並用所需顏色填充它。此過程允許我們生成純色影像,這對於建立背景、佔位符或簡單圖形等各種用途非常有用。

在 Pillow 中,我們有名為 `new()` 的方法,用於使用顏色建立影像。在開始時,我們已經看到了 `Image` 模組中可用的 `new()` 方法的語法和引數。

使用定義的顏色建立影像需要遵循幾個步驟。讓我們逐一檢視它們。

  • 匯入必要的模組

    要使用 Pillow,我們需要匯入所需的模組,通常是 `Image` 和 `ImageDraw`。`Image` 模組提供用於建立和操作影像的函式,而 `ImageDraw` 用於在影像上繪製形狀和文字。

  • 定義影像大小和顏色

    確定我們要建立的影像的尺寸(即寬度和高度),並指定要使用的顏色。顏色可以透過多種方式定義,例如 RGB 元組或顏色名稱。

  • 使用指定的大小和顏色建立一個新影像

    使用 `Image.new()` 方法建立一個新影像。我們可以指定影像模式,可以是“RGB”、“RGBA”、“L”(灰度)以及其他模式,具體取決於我們的需求。我們還可以為影像提供大小和顏色。

  • 可選:在影像上繪製

    如果我們想向影像新增形狀、文字或其他元素,則可以使用 `ImageDraw` 模組。這允許我們使用各種方法(如 `draw.text()`、`draw.rectangle()` 等)在影像上繪製。

  • 儲存或顯示影像

    我們可以使用 `save()` 方法將建立的影像儲存到特定格式(例如 PNG、JPEG)的檔案中。或者,我們可以使用 `show()` 方法顯示影像,該方法會在預設影像檢視器中開啟影像。

示例

在這個示例中,我們使用 `Image` 模組的 `new()` 方法建立一個純紅色影像。

from PIL import Image, ImageDraw

#Define image size (width and height)
width, height = 400, 300

#Define the color in RGB format (e.g., red)
color = (255, 0, 0)  

#Red
#Create a new image with the specified size and color
image = Image.new("RGB", (width, height), color)

#Save the image to a file
image.save("output Image/colored_image.png")

#Show the image (opens the default image viewer)
image.show()

輸出

colored imagedraw

示例

在這個示例中,我們使用了可選功能,即使用 `ImageDraw` 模組的 `Draw()` 方法新增文字。

from PIL import Image, ImageDraw

#Define image size (width and height)
width, height = 400, 300

#Define the color in RGB format (e.g., red)
color = (255, 0, 0)  

#Red
#Create a new image with the specified size and color
image = Image.new("RGB", (width, height), color)

#Optional: If you want to draw on the image, use ImageDraw
draw = ImageDraw.Draw(image)
draw.text((10, 10), "Hello, Welcome to Tutorialspoint", fill=(255, 255, 255))  

#Draw white text at position (10, 10)
#Save the image to a file
image.save("output Image/colored_image.png")

#Show the image (opens the default image viewer)
image.show()

輸出

colored imagedraw tp
廣告