【python】给图片外围添加边框(pillow)

测试样例

画师来源编号
藤原pixiv77869081

在这里插入图片描述

成果展示

在这里插入图片描述

安装模块

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))

参数说明

参数类型描述
srcstr输入路径
dststr保存路径
locstr边框位置
widthint边框大小
colorint 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
  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Xavier Jiezou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值