You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python Pillow图像设置不同X、Y方向的扩展边框?

实现Pillow图像X/Y维度不同扩展边框的方法

Pillow自带的工具就能搞定这个需求,不用额外折腾,下面两种方法任选:

方法一:用ImageOps.expand()直接加边框

这个函数支持传入四元组(左, 上, 右, 下)来分别设置四个边的边框宽度,轻松实现X(左右)和Y(上下)维度不同的扩展——甚至四个边都能单独设置不同宽度。

示例代码:

from PIL import Image, ImageOps

# 打开目标图像
img = Image.open("your_image.jpg")

# 左右各加100px边框,上下各加50px边框,背景色设为白色
expanded_img = ImageOps.expand(img, border=(100, 50, 100, 50), fill="white")

# 保存或查看结果
expanded_img.save("expanded_result.jpg")
expanded_img.show()

方法二:用Image.pad()自定义画布尺寸

如果需要更精确控制最终图像的整体尺寸,可以先创建一个更大的画布,再把原图像粘贴进去,指定偏移量就能实现不同边的扩展。

示例代码:

from PIL import Image

img = Image.open("your_image.jpg")

# 计算目标画布尺寸:原宽度+200px(左右各100),原高度+100px(上下各50)
target_size = (img.width + 200, img.height + 100)

# 创建白色背景的新画布
padded_img = Image.new("RGB", target_size, "white")
# 把原图像粘贴到新画布上,左上角偏移(100,50),对应左右各留100,上下各留50
padded_img.paste(img, (100, 50))

# 保存或查看
padded_img.save("padded_result.jpg")
padded_img.show()

嫌上面步骤麻烦的话,也可以用ImageOps.pad()一步到位:

from PIL import Image, ImageOps

img = Image.open("your_image.jpg")
# 直接指定目标尺寸,设置背景色和居中对齐
padded_img = ImageOps.pad(img, (img.width+200, img.height+100), color="white", centering=(0.5, 0.5))

两种方法的小区别

  • ImageOps.expand()更聚焦于“加边框”,参数直接对应边框宽度,上手快。
  • Image.pad()系列更偏向“适配画布”,适合需要严格控制最终图像尺寸的场景。

内容的提问来源于stack exchange,提问作者worte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:10:41