python图片压缩软件_python 无损压缩照片,支持批量压缩,支持保留照片信息

1 #-*- coding: utf-8 -*-

2

3 """脚本功能说明:使用 tinypng api,一键批量压缩指定文件(夹)所有文件"""

4

5 importos6 importsys7 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor #线程池,进程池

8 importjson9 importrandom10 importrequests11 from you_get importcommon12 from shutil importcopyfile13

14

15 defget_file_dir(file):16 """获取文件目录通用函数"""

17 fullpath =os.path.abspath(os.path.realpath(file))18 returnos.path.dirname(fullpath)19

20

21 defcheck_suffix(file_path):22 """检查指定文件的后缀是否符合要求"""

23 file_path_lower =file_path.lower()24 return (file_path_lower.endswith('.png')25 or file_path_lower.endswith('.jpg')26 or file_path_lower.endswith('.jpeg'))27

28

29 defdownload_tinypng(input_file, url, output_file):30 file_name =os.path.basename(input_file)31 arr = file_name.split('.')32 new_file_name = arr[len(arr) - 2] + '_compress'

33 new_output_file = os.path.join(os.path.dirname(output_file), arr[len(arr) - 2] + '_compress.' + arr[len(arr) - 1])34 print(u'开始下载文件 :%s' %new_output_file)35 #print(os.path.splitext(os.path.basename(output_file))[0])

36 sys.argv = ['you-get', '-o', os.path.dirname(37 output_file), '-O', new_file_name, url]38 common.main()39 old_size =os.path.getsize(input_file)40 new_size =os.path.getsize(new_output_file)41 print(u'文件保存地址:%s' %new_output_file)42 print(u'压缩后文件大小:%d KB' % (new_size / 1024))43 print(u'压缩比: %d%%' % ((old_size - new_size) * 100 /old_size))44

45

46 defcompress_by_tinypng(input_file):47 if notcheck_suffix(input_file):48 print(u'只支持png\\jpg\\jepg格式文件:' +input_file)49 return

50

51 file_name =os.path.basename(input_file)52 arr = file_name.split('.')53 new_file_name = arr[len(arr) - 2] + '_compress.' + arr[len(arr) - 1]54 output_path = os.path.join(get_file_dir(input_file), 'compress_output')55 output_file =os.path.join(output_path, new_file_name)56 if notos.path.isdir(output_path):57 os.makedirs(output_path)58

59 if(os.path.exists(output_file)):60 print("已存在,跳过压缩")61 return

62

63 try:64 old_size =os.path.getsize(input_file)65 print(u'压缩前文件名:%s文件大小:%d KB' % (input_file, old_size / 1024))66 if (old_size < 1024 * 1024):67 print("已跳过压缩,并直接拷贝文件")68 try:69 copyfile(input_file, output_file)70 exceptIOError as e:71 print("Unable to copy file. %s" %e)72 return

73 print("开始压缩")74 shrink_image(input_file)75 print(u'文件压缩成功:%s' %input_file)76 #download_thread_pool.submit(download_tinypng, source, input_file, output_file)

77 exceptException as e:78 print(u'报错了:%s' %e)79

80

81 defcheck_path(input_path):82 """如果输入的是文件则直接压缩,如果是文件夹则先遍历"""

83 ifos.path.isfile(input_path):84 compress_by_tinypng(input_path)85 elifos.path.isdir(input_path):86 dirlist =os.walk(input_path)87 for root, dirs, files indirlist:88 if (not (root.endswith("\\compress_output") or root.endswith("/compress_output"))):89 i =090 for filename infiles:91 i = i + 1

92 process_pool.submit(compress_by_tinypng, os.path.join(93 root, filename))94 #compress_by_tinypng(os.path.join(root, filename))

95 else:96 print(u'目标文件(夹)不存在,请确认后重试。')97

98

99 deflist_images(path):100 images =None101 try:102 ifpath:103 os.chdir(path)104 full_path =os.getcwd()105 files =os.listdir(full_path)106 images =[]107 for file infiles:108 ext = os.path.splitext(file)[1].lower()109 if ext in ('.jpg', '.jpeg', '.png'):110 images.append(os.path.join(full_path, file))111 except:112 pass

113 returnimages114

115

116 defshrink_image(file_path):117 print(u'源文件地址:%s' %file_path)118 result =shrink(file_path)119 ifresult:120 output_path =generate_output_path(file_path)121 url = result['output']['url']122 print(u'下载地址:%s' %url)123 download_tinypng(file_path, url, output_path)124 #download_thread_pool.submit(download_tinypng, file_path, url, output_path)

125 #response = requests.get(url)

126 #with open(output_path, 'wb') as file:

127 #file.write(response.content)

128 #print(u'文件保存地址:%s' % output_path)

129 #print('%s %d=>%d(%f)' % (

130 #result['input']['type'],

131 #result['input']['size'],

132 #result['output']['size'],

133 #result['output']['ratio']

134 #))

135 else:136 print('压缩失败')137

138

139 defshrink(file_path):140 url = 'https://tinypng.com/web/shrink'

141 headers ={142 'Cache-Control': 'no-cache',143 'Content-Type': 'application/x-www-form-urlencoded',144 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.44',145 'X-Forwarded-For': get_random_ip()146 }147 result =None148 try:149 file = open(file_path, 'rb')150 response = requests.post(url, headers=headers, data=file)151 result =json.loads(response.text)152 exceptException as e:153 print(u'报错了:%s' %e)154 iffile:155 file.close()156 if result and result['input'] and result['output']:157 returnresult158 else:159 returnNone160

161

162 defgenerate_output_path(file_path):163 parent_path =os.path.abspath(os.path.dirname(file_path))164 output_path = os.path.join(parent_path, 'compress_output')165 if notos.path.isdir(output_path):166 os.mkdir(output_path)167 returnos.path.join(output_path, os.path.basename(file_path))168

169

170 defget_random_ip():171 ip =[]172 for i in range(4):173 ip.append(str(random.randint(0 if i in (2, 3) else 1, 254)))174 return '.'.join(ip)175

176

177 if __name__ == '__main__':178 thread_pool = ThreadPoolExecutor(5) #定义5个线程执行此任务

179 download_thread_pool = ThreadPoolExecutor(10) #定义5个线程执行此任务

180 process_pool = ProcessPoolExecutor(8) #定义5个进程

181 len_param =len(sys.argv)182 if len_param != 2 and len_param != 3:183 print('请使用: %s [filepath]' %os.path.basename(sys.argv[0]))184 else:185 check_path(sys.argv[1])186 input("Press 请耐心等待\n")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值