前言

  • 本文次要是为了给宽图片高低补边
  • 试验环境
Windows 10 2004Python 3.8.3Pillow 7.1.2

代码

# encoding: utf-8# author: qbit# date: 2020-09-2# summary: 给宽图片高低补白边,让其满足肯定比例,而后缩放到指定尺寸import mathfrom PIL import Imagedef add_white_edge(inImgPath, outImgPath, width, height):    r"""    给宽图片高低补白边,让其满足肯定比例,而后缩放到指定尺寸    inImgPath: 输出图片门路    outImgPath: 输入图片门路    width: 最终宽度    height: 最终高度    """    print(f'{inImgPath}')    inImg: Image.Image = Image.open(inImgPath)    bgWidth = inImg.width    bgHeight = inImg.height    if bgWidth > bgHeight:        bgHeight = math.ceil((bgWidth * height) / width)    # 创立一个红色背景图片    bgImg: Image.Image = Image.new("RGB", (bgWidth, bgHeight), (255, 255, 255))    bgImg.paste(inImg, (0, round((bgHeight - inImg.height) / 2)))    bgImg.resize((width, height), Image.LANCZOS).save(outImgPath)if __name__ == "__main__":    add_white_edge('wide.jpg', 'wide_out.jpg', 108, 150)

示例

  • 输出图片样例(点击图片查看边框

  • 输入图片样例(点击图片查看边框

相干浏览

  • Python 去除图片纯色边框
本文出自 qbit snap