💡Python图像处理实战:打造一个命令行图片尺寸调整工具(含完整源码)

35次阅读
没有评论

共计 2064 个字符,预计需要花费 6 分钟才能阅读完成。

🖼️ 想快速批量调整图片大小?只需一段 Python 代码就能搞定!本文带你从 0 编写一个简单实用的命令行图片尺寸调整工具,适合博客配图、网页优化等场景!


📌 项目简介

在日常工作或内容创作中,我们经常会遇到需要调整图片尺寸的情况,比如:

  • 为博客或公众号压缩大图;
  • 给网站上传合适尺寸的封面图;
  • 降低图片文件体积以加快加载速度。

本文将用 Python 编写一个命令行图片缩放工具,支持自定义输入输出路径、自动判断文件扩展名、处理异常情况,并且可以自由设置目标宽高。


🧰 所需环境

本工具基于 Pillow 图像处理库:

pip install pillow

🧠 功能亮点

  • ✅ 支持常见图片格式:.jpg, .jpeg, .png, .bmp, .gif
  • ✅ 自动补全扩展名
  • ✅ 输入 / 输出路径检查
  • ✅ 尺寸合法性校验
  • ✅ 命令行交互式操作

📜 完整源码

from PIL import Image
import os
import sys

def resize_image(input_path, output_path, width, height):
    """按照指定尺寸调整图片大小"""
    try:
        with Image.open(input_path) as img:
            # 确保输出目录存在
            output_dir = os.path.dirname(output_path)
            if output_dir and not os.path.exists(output_dir):
                os.makedirs(output_dir)

            # 调整图片大小并保存
            resized_img = img.resize((width, height), Image.LANCZOS)
            resized_img.save(output_path)
        return True
    except Exception as e:
        print(f"处理图片时出错: {e}")
        return False

def get_valid_file_path(prompt, default_ext='.jpg', valid_exts=None):
    """获取有效的文件路径,处理扩展名问题"""
    if valid_exts is None:
        valid_exts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']

    while True:
        path = input(prompt).strip()
        if not path:
            print("错误: 路径不能为空")
            continue

        ext = os.path.splitext(path)[1].lower()
        if not ext:
            path += default_ext
            print(f"未指定扩展名,默认使用 {default_ext}")
            return path
        elif ext in valid_exts:
            return path
        else:
            print(f"错误: 不支持的文件扩展名'{ext}'")
            print(f"支持的扩展名: {', '.join(valid_exts)}")

def main():
    """程序主函数"""
    print("=== 图片尺寸调整工具 ===")

    input_path = get_valid_file_path("请输入要处理的图片路径:")
    if not os.path.exists(input_path):
        print(f"错误: 文件'{input_path}'不存在")
        sys.exit(1)

    output_path = get_valid_file_path("请输入处理后图片的保存路径:")

    while True:
        try:
            width = int(input("请输入目标宽度 ( 像素):").strip())
            height = int(input("请输入目标高度 ( 像素):").strip())
            if width <= 0 or height <= 0:
                print("错误: 宽度和高度必须是正整数")
                continue
            break
        except ValueError:
            print("错误: 宽度和高度必须是整数")

    if resize_image(input_path, output_path, width, height):
        print(f"图片已成功调整为 {width}x{height} 并保存至 {output_path}")
    else:
        print("图片调整失败")

if __name__ == "__main__":
    main()

🧪 使用方法

打开命令行或终端,运行脚本:

python resize_tool.py

按提示输入路径和尺寸,例如:

  • 原图路径:test.jpg
  • 新图路径:resized/test_resized.png
  • 宽度 / 高度:800x600

输出结果如下:

 图片已成功调整为 800x600 并保存至 resized/test_resized.png

🛠️ 扩展建议

你可以在此工具的基础上添加更多功能:

  • ✅ 批量处理目录下所有图片
  • ✅ 自动保持原始宽高比
  • ✅ 增加 GUI 界面(比如 Tkinter)
  • ✅ 输出图像压缩质量参数

🔚 结语

通过这篇文章,你已经掌握了如何用 Python 快速构建一个实用的命令行图像缩放工具。如果你觉得对你有帮助,欢迎收藏 + 点赞 + 关注我,一起探索更多 Python 图像处理技巧!

正文完
 0
评论(没有评论)