tinyimg.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. import os
  4. import os.path
  5. import click
  6. import tinify
  7. online_key_list = [
  8. "sq5RzZVjHxVKRN0CHSBn659XPb67PyMl",
  9. "rcj2WmWcPZGMDbmwDXJ69XQKGhyr6mCw",# 可以继续添加 防止一个key不够
  10. ]
  11. online_key_list_iter = iter(online_key_list)
  12. online_key = next(online_key_list_iter)
  13. version = "1.0.1" # 版本
  14. # 压缩的核心
  15. def compress_core(inputFile, outputFile, img_width):
  16. global online_key
  17. compresskey = online_key
  18. tinify.key = compresskey
  19. print "file = %s" % inputFile
  20. try:
  21. source = tinify.from_file(inputFile)
  22. if img_width is not -1:
  23. resized = source.resize(method="scale", width=img_width)
  24. resized.to_file(outputFile)
  25. else:
  26. source.to_file(outputFile)
  27. except tinify.AccountError, e:
  28. online_key = next(online_key_list_iter)
  29. compress_core(inputFile, outputFile, img_width) # 递归方法 继续读取
  30. except tinify.ClientError, e:
  31. print(e)
  32. pass
  33. # 仅压缩指定文件
  34. def compress_file(inputFile, width):
  35. print "compress_file-------------------------------------"
  36. if not os.path.isfile(inputFile):
  37. print "这不是一个文件,请输入文件的正确路径!"
  38. return
  39. basename = os.path.basename(inputFile)
  40. fileName, fileSuffix = os.path.splitext(basename)
  41. if fileSuffix == '.png' or fileSuffix == '.jpg' or fileSuffix == '.jpeg':
  42. compress_core(inputFile, inputFile, width)
  43. else:
  44. print "不支持该文件类型!"
  45. @click.command()
  46. @click.option('-d', "--dir", type=str, default='/', help="压缩文件夹下所有文件")
  47. @click.option('-f', "--file", type=str, default=None, help="单个文件压缩")
  48. @click.option('-s', "--size", type=str, default='1024k', help="需要压缩的文件大小")
  49. @click.option('-w', "--width", type=int, default=-1, help="图片宽度,默认不变")
  50. def run(dir, file, width, size):
  51. if file is not None:
  52. compress_file(file, width) # 仅压缩一个文件
  53. pass
  54. elif dir is not None:
  55. find_path = "find " + dir + " -regex '.*\(jpg\|JPG\|png\|PNG\|jpeg\)' -type f -size +" + size + " | sort -nr"
  56. # print(find_path)
  57. result = os.popen(find_path).read().split('\n')
  58. for item in result:
  59. # print(item)
  60. compress_file(item, width)
  61. pass
  62. pass
  63. else:
  64. print '请指定要压缩的文件或文件夹'
  65. print "结束!"
  66. if __name__ == "__main__":
  67. run()