承接上篇要繼續瞭解如何使用Python PIL函式庫中的圖片處理方法,處理圖片的模組是Image,使用這個函式庫來開啟圖片檔、旋轉圖片或是另存成新的格式圖片等功能。
- mode:設定檔案屬性,僅能填寫'r'。
.旋轉圖片 rotate
- resample:resampling過濾器的選項。'
- expand:擴充的選項,旋轉時會以最大圖片顯示。
.儲存圖片 save
- format:檔案的格式,例如:JPEG、PNG、GIF...等
例如存檔成PNG檔:image.save('avatar.png', 'png')
.建立空白圖片檔 New file
- size:設定圖片寬與高 (width, height)
- color:圖像使用什麼顏色,預設為黑色。
例如:建立一個新的空影像檔:Image.new(mode = "RGB", size = (200, 200), color=0)

[圖形Image基本元素]
.開啟圖片檔 Open filePIL.Image.open(fp, mode='r')- fp:是檔案名稱,或加上路徑名稱。
- mode:設定檔案屬性,僅能填寫'r'。
.旋轉圖片 rotate
Image.rotate(angle, resample=0, expand=0)- angle:是旋轉角度,依順時鐘方向增加。
- resample:resampling過濾器的選項。'
- expand:擴充的選項,旋轉時會以最大圖片顯示。
.儲存圖片 save
Image.save(fp, format=None, **params)- fp:是檔案名稱,或加上路徑名稱。
- format:檔案的格式,例如:JPEG、PNG、GIF...等
例如存檔成PNG檔:image.save('avatar.png', 'png')
.建立空白圖片檔 New file
PIL.Image.new(mode, size, color=0)- mode:設定檔案解析度,可以是RGB、CMYK、LAB等多種格式。
- size:設定圖片寬與高 (width, height)
- color:圖像使用什麼顏色,預設為黑色。
例如:建立一個新的空影像檔:Image.new(mode = "RGB", size = (200, 200), color=0)
[程式]
# !/usr/bin/python
# coding:utf-8
from PIL import Image
import sys
import ST7735 as TFT
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.SPI as SPI
# 定義LCD的長寬
WIDTH = 128
HEIGHT = 160
SPEED_HZ = 4000000
# 樹莓派設定
DC = 24
RST = 25
SPI_PORT = 0
SPI_DEVICE = 0
# 建立 TFT LCD 顯示類別
disp = TFT.ST7735(
DC,
rst=RST,
spi=SPI.SpiDev(
SPI_PORT,
SPI_DEVICE,
max_speed_hz=SPEED_HZ))
# 初始化顯示
disp.begin()
# 載入一張圖片
print('Loading image...')
image = Image.open('avatar.jpg')
# 存檔成png檔
image.save('avatar.png', 'png')
# 更改圖片大小,並旋轉使其適合顯示大小.
image = image.rotate(90).resize((WIDTH, HEIGHT))
# 繪製圖片在顯示器硬體上
print('Drawing image')
print(image.format, image.size, image.mode)
disp.display(image)
[執行結果]
產生的圖片 PNG檔,如下圖紅色箭頭處:
張貼留言