fujian_water_biz_doc/scripts/resize_image.py

125 lines
3.9 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
福建水务营收系统 - 图片尺寸调整工具
限制图片高度不超过23公分约870像素
"""
import argparse
import os
import sys
from PIL import Image
def resize_image_height(image_path, max_height_cm=23, dpi=96):
"""
通过调整DPI元数据控制图片打印高度限制在指定厘米范围内
Args:
image_path (str): 图片文件路径
max_height_cm (float): 最大高度(厘米)
dpi (int): 默认DPI设置用于参考
Returns:
bool: 调整是否成功
"""
try:
# 检查文件是否存在
if not os.path.exists(image_path):
print(f"❌ 错误: 文件不存在 {image_path}")
return False
# 打开图片
with Image.open(image_path) as img:
original_width, original_height = img.size
# 获取当前DPI如果存在
current_dpi = img.info.get("dpi", (dpi, dpi))
if isinstance(current_dpi, (list, tuple)):
current_dpi_value = current_dpi[0]
else:
current_dpi_value = current_dpi
# 计算当前图片的物理高度(厘米)
current_height_cm = original_height / current_dpi_value * 2.54
print("📏 图片信息:")
print(f" 像素尺寸: {original_width}x{original_height}px")
print(f" 当前DPI: {current_dpi_value}")
print(f" 当前打印高度: {current_height_cm:.2f}cm")
# 检查是否需要调整
if current_height_cm <= max_height_cm:
print(f"✅ 图片打印高度 {current_height_cm:.2f}cm 符合要求,无需调整")
return True
# 计算新的DPI以满足高度要求
# 新DPI = 原始像素高度 / (目标高度厘米 / 2.54)
required_dpi = original_height / (max_height_cm / 2.54)
print("🔧 调整DPI元数据:")
print(f" 原始DPI: {current_dpi_value}")
print(f" 调整后DPI: {required_dpi:.0f}")
print(f" 目标打印高度: {max_height_cm}cm")
print(f" 像素尺寸保持不变: {original_width}x{original_height}px")
# 创建新图片并设置DPI元数据
new_img = img.copy()
# 保存图片时设置新的DPI
new_img.save(
image_path, dpi=(required_dpi, required_dpi), optimize=True, quality=95
)
print(f"✅ 图片DPI元数据调整完成: {image_path}")
print(f" 现在图片将以 {max_height_cm}cm 高度打印")
return True
except Exception as e:
print(f"❌ 图片处理失败: {str(e)}")
return False
def main():
"""主函数"""
parser = argparse.ArgumentParser(
description="调整图片高度限制在23公分内",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
python resize_image.py image.png
python resize_image.py image.png --max-height 20
python resize_image.py image.png --dpi 300
""",
)
parser.add_argument("image_path", help="要处理的图片文件路径")
parser.add_argument(
"--max-height", type=float, default=23.0, help="最大高度厘米默认23厘米"
)
parser.add_argument("--dpi", type=int, default=96, help="DPI设置默认96")
parser.add_argument("--verbose", action="store_true", help="显示详细信息")
args = parser.parse_args()
# 处理图片
if args.verbose:
print("🔧 图片处理参数:")
print(f" 文件: {args.image_path}")
print(f" 最大高度: {args.max_height}cm")
print(f" DPI: {args.dpi}")
print()
success = resize_image_height(args.image_path, args.max_height, args.dpi)
# 返回适当的退出代码
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()