本工具是通过将图片上传到第三方网站tinypng,进行压缩后下载,覆盖本地图片,tinypng是一个强大的图片处理网站,目前最可靠的无损压缩网站。
代码如下:
import requests
from idna import unicode
from selenium import webdriver
import time
import os
browser = webdriver.Firefox(executable_path='/Users/lyf/Library/Google/geckodriver')
def tiny_png(url):
# browser.get('https://tinypng.com/')
upload_file = browser.find_element_by_tag_name("input")
try:
upload_file.send_keys(url)
browser.implicitly_wait(20)
a = browser.find_element_by_link_text('download')
img_url = a.get_attribute('href')
print(img_url)
r = requests.get(img_url)
with open(url, 'wb') as f:
f.write(r.content)
browser.refresh()
time.sleep(2)
except Exception as e:
print(e)
def is_need_compress(img_path):
"""
判断是否需要压缩处理 >10k 进行压缩处理
:param img_path:
:return:
"""
if img_path.endswith('.jpg') or img_path.endswith('.png'):
size = os.path.getsize(img_path) / 1024
if size > 10.0:
print('文件大小:%sk' % size)
return True
return False
def file_loop(file_path):
"""
遍历文件夹
:param file_path:
:return:
"""
files = os.listdir(file_path)
for fi in files:
fi_d = os.path.join(file_path, fi)
if os.path.isdir(fi_d):
file_loop(fi_d)
else:
child_path = os.path.join(file_path, fi_d)
print(child_path)
if is_need_compress(child_path):
tiny_png(child_path)
if __name__ == "__main__":
file_path = "/Users/lyf/AndroidStudioProjects/fubei/new-fubei-android-2.5-up/app/src/main/assets/www/assets"
browser.get('https://tinypng.com/')
file_loop(file_path)