Python 图片处理:裁剪缩放至300×200,格式JPG/PNG/GIF,控制大小≤100KB

Python 图片处理:裁剪缩放至300×200,格式JPG/PNG/GIF,控制大小≤100KB

使用Pillow库,功能:

  1. 强制输出尺寸 300 × 200
  2. 支持输入 JPG,PNG,GIF
  3. 循环调节质量,把文件压到100KB以内
  4. 保存输出文件

安装依赖

复制代码
pip install pillow

完整代码

复制代码
from PIL import Image
import os

def process_image(input_path: str, output_path: str, target_size=(300, 200), max_kb=100):
    """
    处理图片:缩放裁剪到300x200,文件不超过100KB
    :param input_path: 原始图片路径
    :param output_path: 输出保存路径
    :param target_size: (宽,高) 目标尺寸 300*200
    :param max_kb: 最大文件大小 KB
    """
    max_bytes = max_kb * 1024
    width, height = target_size

    img = Image.open(input_path)

    # 缩放+居中裁剪到固定300×200
    img = img.resize(target_size, Image.Resampling.LANCZOS)

    # 区分格式处理
    ext = os.path.splitext(output_path)[1].lower()
    quality = 95

    if ext in [".jpg", ".jpeg"]:
        # JPG 循环降低质量控制体积
        while True:
            img.save(output_path, format="JPEG", quality=quality, optimize=True)
            fsize = os.path.getsize(output_path)
            if fsize <= max_bytes or quality <= 10:
                break
            quality -= 5

    elif ext == ".png":
        img.save(output_path, format="PNG", optimize=True)

    elif ext == ".gif":
        img.save(output_path, format="GIF", optimize=True)

    final_size = os.path.getsize(output_path) / 1024
    print(f"已保存 {output_path} | 尺寸 {img.size} | 文件大小 {final_size:.2f} KB")


if __name__ == "__main__":
    # ========== 修改这里你的输入输出路径 ==========
    INPUT_FILE = "test.png"   # 你的原图
    OUTPUT_FILE = "out.jpg"   # 输出,后缀 .jpg/.png/.gif

    try:
        process_image(INPUT_FILE, OUTPUT_FILE, target_size=(300, 200), max_kb=100)
    except Exception as e:
        print(f"处理出错:{e}")

使用说明

  1. 修改 INPUT_FILE 为你的图片文件路径
  2. 修改 OUTPUT_FILE 设置输出文件名,后缀决定输出格式 .jpg / .png / .gif
  3. 输出强制固定 宽300px,高200px
  4. JPG会自动降低画质,保证文件小于100KB;PNG/GIF受编码限制,如果原图色彩复杂有可能略超100KB。

如果你需要:批量处理文件夹全部图片、不裁剪改为等比例缩放留黑边、或者GUI版本,告诉我,我直接改代码。

相关推荐
2601_962294611 小时前
Python工具软件开发:借助InsCode AI IDE开启智能编程新时代
ide·python·ai·开发工具·智能化编程
2601_962097363 小时前
GraphQL,Grafana和Dash
python·grafana·数据可视化·graphql·dash
_阿南_8 小时前
项目中新增给AI制定的代码规范
前端·程序员
青禾8379 小时前
Linux 操作系统入门指南:从目录结构到常用命令
linux·运维·服务器
名字还没想好☜9 小时前
React 实现暗黑模式切换:localStorage 持久化、SSR 首屏闪烁与跟随系统主题
前端·javascript·react.js·ecmascript·react·next.js
闖6410 小时前
入门Linux操作系统|零基础吃透原理、目录、权限、常用命令
linux
console.log('npc')10 小时前
Git 冲突与 AI 协助指南
前端·人工智能·git·大模型
benchmark_cc10 小时前
REST API 和 Python SDK 应该怎么选?量化交易数据接口选型实战
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
bruk_spp10 小时前
linux pinctrl
linux