前言本文主要针对宽幅图片的上下边缘进行填充。测试环境为Windows102004Python3.8.3Pillow7.1.2code#encoding:utf-8#author:qbit#date:2020-09-2#summary:填充宽图片的上下边缘,让它满足一定比例,然后缩放到指定尺寸importmathfromPILimportImagedefadd_white_edge(inImgPath,outImgPath,width,height):r"""填充宽图的上下边缘,让它满足一定的比例,然后缩放到指定大小inImgPath:输入图片路径outImgPath:输出图片路径width:finalwidthheight:finalheight"""print(f'{inImgPath}')inImg:Image.Image=Image.open(inImgPath)bgWidth=inImg.widthbgHeight=inImg.heightifbgWidth>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)Sample输入图片样本(点击图片查看边框)输出图片样本(点击图片查看边框)相关阅读Python去除图片纯色框架文字来自qbitsnap
