测试样例

画师 来源 编号
藤原 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

本文地址:https://blog.csdn.net/qq_42951560/article/details/109890903