測試樣例
畫師 | 來源 | 編號 |
---|---|---|
藤原 | pixiv | 77869081 |
成果展示
安裝模塊
pip install pillow
源碼發布
from PIL import Image
def image_border(src, dst, loc='a', width=3, color=(0, 0, 0)):
''' src: (str) 需要加邊框的圖片路徑 dst: (str) 加邊框的圖片保存路徑 loc: (str) 邊框添加的位置, 默認是'a'( 四周: 'a' or 'all' 上: 't' or 'top' 右: 'r' or 'rigth' 下: 'b' or 'bottom' 左: 'l' or 'left' ) width: (int) 邊框寬度 (默認是3) color: (int or 3-tuple) 邊框顏色 (默認是0, 表示黑色; 也可以設置為三元組表示RGB顏色) '''
# 讀取圖片
img_ori = Image.open(src)
w = img_ori.size[0]
h = img_ori.size[1]
# 添加邊框
if loc in ['a', 'all']:
w += 2*width
h += 2*width
img_new = Image.new('RGB', (w, h), color)
img_new.paste(img_ori, (width, width))
elif loc in ['t', 'top']:
h += width
img_new = Image.new('RGB', (w, h), color)
img_new.paste(img_ori, (0, width, w, h))
elif loc in ['r', 'right']:
w += width
img_new = Image.new('RGB', (w, h), color)
img_new.paste(img_ori, (0, 0, w-width, h))
elif loc in ['b', 'bottom']:
h += width
img_new = Image.new('RGB', (w, h), color)
img_new.paste(img_ori, (0, 0, w, h-width))
elif loc in ['l', 'left']:
w += width
img_new = Image.new('RGB', (w, h), color)
img_new.paste(img_ori, (width, 0, w, h))
else:
pass
# 保存圖片
img_new.save(dst)
if __name__ == "__main__":
image_border('old.jpg', 'new.jpg', 'a', 10, color=(255, 0, 0))
參數說明
參數 | 類型 | 描述 |
---|---|---|
src | str | 輸入路徑 |
dst | str | 保存路徑 |
loc | str | 邊框位置 |
width | int | 邊框大小 |
color | int or 3-tuple | 邊框顏色 |
代碼核心
PIL.Image.new(mode, size, color=0)
- 描述
這是Image
的全局函數,用於創建一個新畫布。
- 參數
mode
:顏色模式。如'RGB'
表示真彩色。
size
:畫布大小。如(5, 3)
表示創建一個寬為5、高為3的畫布。
color
:填充顏色。默認為0
表示黑色,也可以設置為3元組的RGB值。
Image.paste(im, box=None, mask=None)
- 描述
這是Image
的類方法,用於圖片填充或粘貼。
- 參數
im
:待插入的圖片。
box
:圖片插入的位置。
mask
:遮罩。
引用參考
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.new
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.paste