您当前的位置: 首页 >  Python

Xavier Jiezou

暂无认证

  • 1浏览

    0关注

    394博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

Xavier Jiezou 发布时间:2020-11-21 10:49:12 ,浏览量:1

测试样例 画师来源编号藤原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
关注
打赏
1661408149
查看更多评论
立即登录/注册

微信扫码登录

0.0436s