compress.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. # print(item)
  23. if not os.path.isfile(item):
  24. print "这不是一个文件 file = %s" % item
  25. return
  26. basename = os.path.basename(item)
  27. fileName, fileSuffix = os.path.splitext(basename)
  28. #if fileSuffix != '.png' and fileSuffix != '.jpg' and fileSuffix == '.jpeg':
  29. # print "不支持该文件类型! file = %s" % item
  30. # return
  31. try:
  32. img = Image.open(item)
  33. except IOError:
  34. print(file)
  35. x, y = img.size
  36. if x >= width:
  37. convert_path = "convert -resize 50%x50% " + item + ' ' +item
  38. print(item)
  39. os.popen(convert_path)
  40. if __name__ == "__main__":
  41. run()