一、Pillow 簡介
Pillow 是 Python 圖像處理庫 PIL(Python Imaging Library)的友好分支,是圖像處理的事實標準。它支持打開、編輯、轉換、保存多種圖像格式,常用于圖像批量處理、驗證碼識別、縮略圖生成等應用場景。
二、安裝 Pillow
2.1 使用 pip 安裝(推薦)
pip install Pillow
2.2 驗證安裝
import PIL
print(PIL.__version__)
若無報錯且輸出版本號,則說明安裝成功。
三、基本使用示例
3.1 打開圖像
from PIL import Imageimg = Image.open("example.jpg")
img.show()
3.2 圖像信息
print(img.format) # 圖像格式(JPEG、PNG 等)
print(img.size) # 圖像尺寸
print(img.mode) # 顏色模式(RGB、L 等)
3.3 圖像保存
img.save("output.png")
四、常見圖像操作
4.1 縮放與裁剪
resized = img.resize((200, 200))
cropped = img.crop((100, 100, 300, 300)) # 左、上、右、下
4.2 旋轉與翻轉
rotated = img.rotate(45) # 順時針旋轉 45°
flipped = img.transpose(Image.FLIP_LEFT_RIGHT) # 左右翻轉
4.3 轉換顏色模式
gray = img.convert("L") # 轉為灰度圖
rgba = img.convert("RGBA") # 轉為帶透明通道的圖像
五、繪圖與文字處理
from PIL import ImageDraw, ImageFontdraw = ImageDraw.Draw(img)
draw.rectangle((50, 50, 150, 150), outline="red")
draw.text((60, 60), "Hello", fill="blue")
使用自定義字體:
font = ImageFont.truetype("arial.ttf", 24)
draw.text((10, 10), "你好", font=font, fill="black")
六、圖像濾鏡與增強
from PIL import ImageFilterblurred = img.filter(ImageFilter.BLUR)
contour = img.filter(ImageFilter.CONTOUR)
七、批量圖像處理
import osfor filename in os.listdir("images"):if filename.endswith(".jpg"):img = Image.open(f"images/{filename}")img.thumbnail((300, 300))img.save(f"thumbnails/{filename}")
八、常見問題
Q1: 報錯 OSError: cannot open resource
?
字體文件路徑不正確,使用絕對路徑或將字體文件放入項目目錄中。
Q2: 中文無法顯示?
需要使用支持中文的字體,如 simhei.ttf
或 msyh.ttf
,并加載為 ImageFont.truetype()
。
九、學習資源推薦
- Pillow 官方文檔
- 菜鳥教程 Pillow 教程
- Pillow 示例合集 GitHub
本文由“小奇Java面試”原創發布,轉載請注明出處。
可以搜索【小奇JAVA面試】第一時間閱讀,回復【資料】獲取福利,回復【項目】獲取項目源碼,回復【簡歷模板】獲取簡歷模板,回復【學習路線圖】獲取學習路線圖。