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

如何将矩形图片调整为任意矩形尺寸并居中(保持比例、黑背景填充)

嘿,我完全get到你的需求啦——之前是把图片转成正方形,现在要改成指定的任意矩形尺寸,还要让原图按比例缩放后居中,用黑色填充空白区域。我帮你调整了代码,每一步都加了注释,好懂又好用:

调整后的代码实现
from PIL import Image

def fix_size(input_path, output_path, target_size, background=(0, 0, 0)):
    # 打开原始图片
    with Image.open(input_path) as img:
        # 获取原始图片和目标尺寸的宽高
        img_width, img_height = img.size
        target_width, target_height = target_size
        
        # 计算缩放比例:取宽/高方向的最小比例,保证图片能完整放入目标矩形
        scale = min(target_width / img_width, target_height / img_height)
        
        # 计算缩放后的图片尺寸(转成整数避免像素偏差)
        new_width = int(img_width * scale)
        new_height = int(img_height * scale)
        
        # 用LANCZOS滤镜缩放图片,这是PIL里画质最优的缩放算法
        scaled_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
        
        # 创建目标尺寸的背景图,默认黑色填充
        background_img = Image.new("RGB", target_size, background)
        
        # 计算居中粘贴的坐标:(目标尺寸-缩放后尺寸)的一半,保证完全居中
        paste_x = (target_width - new_width) // 2
        paste_y = (target_height - new_height) // 2
        
        # 把缩放后的图片粘贴到背景图的居中位置
        background_img.paste(scaled_img, (paste_x, paste_y))
        
        # 保存最终处理好的图片
        background_img.save(output_path)
使用说明
  • 调用时只需要传入原始图片路径、输出路径和目标矩形尺寸就行,比如:
    # 示例:把input.jpg转成800×400的矩形,居中+黑背景,保存为output.jpg
    fix_size("input.jpg", "output.jpg", (800, 400))
    
  • 如果需要更换背景色,直接修改background参数即可,比如background=(255,255,255)就是白色背景。
  • 缩放用的LANCZOS滤镜,不管是放大还是缩小图片,都能最大程度保留画质细节。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:59:14