cut.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. #!/usr/bin/env python3
  2. """
  3. PNG图片剪切脚本
  4. 支持通过命令行参数指定上下左右四个方向的剪切像素
  5. """
  6. import argparse
  7. import sys
  8. from PIL import Image
  9. import os
  10. def crop_image(input_path, output_path, top=0, bottom=0, left=0, right=0):
  11. """
  12. 剪切PNG图片
  13. Args:
  14. input_path: 输入图片路径
  15. output_path: 输出图片路径
  16. top: 上方剪切像素数
  17. bottom: 下方剪切像素数
  18. left: 左侧剪切像素数
  19. right: 右侧剪切像素数
  20. """
  21. try:
  22. # 打开图片
  23. with Image.open(input_path) as img:
  24. # 转换为RGB模式(确保兼容性)
  25. if img.mode != 'RGB':
  26. img = img.convert('RGB')
  27. width, height = img.size
  28. print(f"原图尺寸: {width} x {height}")
  29. # 计算剪切后的尺寸
  30. new_width = width - left - right
  31. new_height = height - top - bottom
  32. # 验证剪切参数是否有效
  33. if new_width <= 0 or new_height <= 0:
  34. raise ValueError("剪切后的图片尺寸无效,请检查剪切参数")
  35. if left + right >= width or top + bottom >= height:
  36. raise ValueError("剪切区域超出图片范围")
  37. # 计算剪切区域 (left, top, right, bottom)
  38. crop_box = (left, top, width - right, height - bottom)
  39. # 执行剪切
  40. cropped_img = img.crop(crop_box)
  41. # 保存图片
  42. cropped_img.save(output_path, 'PNG')
  43. print(f"剪切后尺寸: {new_width} x {new_height}")
  44. print(f"图片已保存至: {output_path}")
  45. except FileNotFoundError:
  46. print(f"错误: 找不到输入文件 '{input_path}'")
  47. sys.exit(1)
  48. except Exception as e:
  49. print(f"错误: {e}")
  50. sys.exit(1)
  51. def main():
  52. parser = argparse.ArgumentParser(
  53. description="PNG图片剪切工具",
  54. formatter_class=argparse.RawDescriptionHelpFormatter,
  55. epilog="""
  56. 使用示例:
  57. # 从上方剪切10像素,下方20像素,左侧5像素,右侧15像素
  58. python png_crop.py input.png output.png -t 10 -b 20 -l 5 -r 15
  59. # 只剪切左右各50像素
  60. python png_crop.py input.png output.png -l 50 -r 50
  61. # 只剪切上方100像素
  62. python png_crop.py input.png output.png -t 100
  63. """
  64. )
  65. # 必需参数
  66. parser.add_argument('input', help='输入PNG文件路径')
  67. parser.add_argument('output', help='输出PNG文件路径')
  68. # 剪切参数
  69. parser.add_argument('-t', '--top', type=int, default=0,
  70. help='从上方剪切的像素数 (默认: 0)')
  71. parser.add_argument('-b', '--bottom', type=int, default=0,
  72. help='从下方剪切的像素数 (默认: 0)')
  73. parser.add_argument('-l', '--left', type=int, default=0,
  74. help='从左侧剪切的像素数 (默认: 0)')
  75. parser.add_argument('-r', '--right', type=int, default=0,
  76. help='从右侧剪切的像素数 (默认: 0)')
  77. # 可选参数
  78. parser.add_argument('--overwrite', action='store_true',
  79. help='覆盖已存在的输出文件')
  80. args = parser.parse_args()
  81. # 检查输入文件是否存在
  82. if not os.path.exists(args.input):
  83. print(f"错误: 输入文件 '{args.input}' 不存在")
  84. sys.exit(1)
  85. # 检查输入文件是否为PNG
  86. if not args.input.lower().endswith('.png'):
  87. print("警告: 输入文件可能不是PNG格式,但脚本会尝试处理")
  88. # 检查输出文件是否已存在
  89. if os.path.exists(args.output) and not args.overwrite:
  90. response = input(f"输出文件 '{args.output}' 已存在,是否覆盖? (y/N): ")
  91. if response.lower() not in ['y', 'yes']:
  92. print("操作已取消")
  93. sys.exit(0)
  94. # 检查剪切参数是否为非负数
  95. for param_name, param_value in [('上边', args.top), ('下边', args.bottom),
  96. ('左边', args.left), ('右边', args.right)]:
  97. if param_value < 0:
  98. print(f"错误: {param_name}剪切像素数不能为负数")
  99. sys.exit(1)
  100. # 执行剪切操作
  101. crop_image(args.input, args.output, args.top, args.bottom, args.left, args.right)
  102. if __name__ == "__main__":
  103. main()