compress.py 980 B

123456789101112131415161718192021222324252627282930313233343536
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. import os
  4. import click
  5. from PIL import Image
  6. @click.command()
  7. @click.option('-d', "--dir", type=str, default='/', help="压缩文件夹下所有文件")
  8. @click.option('-w', "--width", type=int, default=1024, help="图片宽度,默认不变")
  9. def run(dir,width):
  10. if dir is not None:
  11. find_path = "find " + dir + " -regex '.*\(jpg\|JPG\|png\|PNG\|jpeg\)' -type f -size 100k | sort -nr"
  12. result = os.popen(find_path).read().split('\n')
  13. for item in result:
  14. compress_file(item, width)
  15. pass
  16. pass
  17. else:
  18. print('请指定要压缩的文件或文件夹')
  19. print('End')
  20. def compress_file(item, width):
  21. if item:
  22. img = Image.open(item)
  23. x, y = img.size
  24. if x >= width:
  25. convert_path = "convert -resize 50%x50% " + item + ' ' +item
  26. print(item)
  27. os.popen(convert_path)
  28. if __name__ == "__main__":
  29. run()