-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimg_tool.py
73 lines (61 loc) · 2.22 KB
/
img_tool.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import os
import pathlib
import shutil
from PIL import Image
# 图片工具类
class ImageOperation:
def __init__(self):
print('init')
@staticmethod
def download(request, url, output_dir, rename):
if url == '':
print('url is empty, please input')
pass
if rename == '':
rename = url.split('/')[-1]
print(rename)
output_path = os.path.join(output_dir, rename)
request_img = request.do_request(url)
with open(output_path, 'wb') as f:
f.write(request_img.content)
# 转为webp格式
@staticmethod
def convert_2_webp(output_dir, path, cover=False):
if path == '':
print('path is empty, please input path')
pass
if not os.path.isfile(path):
print('image does not exist!')
pass
name = pathlib.Path(path).stem
output_path = os.path.join(output_dir, f'{name}.webp')
if os.path.isfile(output_path) and not cover:
print(f'{output_path} already exist')
pass
# 尝试处理所有图片
try:
im = Image.open(path).convert("RGBA")
im.save(output_path, "WEBP")
return True
# 输出处理失败的图片路径
except:
print(f'Error: {path} failed!')
return False
def copy_file(src_file, dst_path):
if not os.path.isfile(src_file):
print(f"{src_file} not exist!")
else:
f_path, f_name = os.path.split(src_file) # 分离文件名和路径
if not os.path.exists(dst_path):
os.makedirs(dst_path) # 创建路径
shutil.copy(src_file, dst_path + f_name) # 复制文件
print("copy %s -> %s" % (src_file, dst_path + f_name))
if __name__ == '__main__':
print('Test')
input_dir_path = os.path.join(os.getcwd(), 'Icons')
output_dir_path = os.path.join(os.getcwd(), 'WebpIcons')
images = os.listdir(input_dir_path)[:6]
# 处理所有图片
for i in range(len(images)):
image_path = os.path.join(input_dir_path, images[i])
ImageOperation.convert_2_webp(output_dir_path, image_path)