26 |
27 |
28 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python -u
2 |
3 | """
4 | Copyright (C) 2017 Jacksgong(jacksgong.com)
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | """
18 | from setuptools import setup, find_packages
19 |
20 | # Get the long description from the README file
21 | # noinspection PyArgumentList
22 | with open('README.md') as f:
23 | long_description = f.read()
24 |
25 | setup(
26 | name="webp-converter",
27 | version="4.1.0",
28 | packages=find_packages(exclude=['arts']),
29 |
30 | # Project uses reStructuredText, so ensure that the docutils get
31 | # installed or upgraded on the target machine
32 | install_requires=['Pillow'],
33 |
34 | # metadata for upload to PyPI
35 | author="Jacksgong",
36 | author_email="igzhenjie@gmail.com",
37 | description="An powerful webp batch converter and differ analytics",
38 | long_description="more detail please move to https://github.com/Jacksgong/webp-converter.",
39 | license="Apache2",
40 | keywords="webp converter",
41 | url="https://github.com/Jacksgong/webp-converter",
42 |
43 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
44 | classifiers=[
45 | # How mature is this project? Common values are
46 | # 3 - Alpha
47 | # 4 - Beta
48 | # 5 - Production/Stable
49 | 'Development Status :: 5 - Production/Stable',
50 |
51 | # Pick your license as you wish (should match "license" above)
52 | 'License :: OSI Approved :: Apache Software License',
53 |
54 | # Specify the Python versions you support here. In particular, ensure
55 | # that you indicate whether you support Python 2, Python 3 or both.
56 | 'Programming Language :: Python :: 2.7',
57 | 'Programming Language :: Python :: 3',
58 | 'Programming Language :: Python :: 3.3',
59 | 'Programming Language :: Python :: 3.4',
60 | 'Programming Language :: Python :: 3.5',
61 | ],
62 | entry_points={
63 | 'console_scripts': [
64 | 'webpc=webpc:main'
65 | ]
66 | }
67 | )
68 |
--------------------------------------------------------------------------------
/webpc/helper.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python -u
2 |
3 | """
4 | Copyright 2017, JacksGong(https://jacksgong.com)
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | """
18 |
19 | import sys
20 | from os import makedirs, environ
21 | from os.path import getsize, join, exists
22 | from shutil import copyfile
23 |
24 | import re
25 |
26 | RESET = '\033[0m'
27 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
28 |
29 | NO_HOME_PATH = re.compile(r'~/(.*)')
30 | HOME_PATH = environ['HOME']
31 |
32 |
33 | # get the home case path
34 | def handle_home_case(path):
35 | path = path.strip()
36 | if path.startswith('~/'):
37 | path = HOME_PATH + '/' + NO_HOME_PATH.match(path).groups()[0]
38 | return path
39 |
40 |
41 | def print_blue(msg):
42 | print(colorize(msg, fg=BLUE))
43 |
44 |
45 | def print_warn(msg):
46 | print(colorize(msg, fg=YELLOW))
47 |
48 |
49 | def termcolor(fg=None, bg=None):
50 | codes = []
51 | if fg is not None: codes.append('3%d' % fg)
52 | if bg is not None: codes.append('10%d' % bg)
53 | return '\033[%sm' % ';'.join(codes) if codes else ''
54 |
55 |
56 | def colorize(message, fg=None, bg=None):
57 | return termcolor(fg, bg) + message + RESET
58 |
59 |
60 | def print_process(message):
61 | print(colorize(message, fg=YELLOW))
62 |
63 |
64 | def size_diff(left, right):
65 | return getsize(left) - getsize(right)
66 |
67 |
68 | def human_bytes(B):
69 | """Return the given bytes as a human friendly KB, MB, GB, or TB string"""
70 | B = float(B)
71 | KB = float(1024)
72 | MB = float(KB ** 2) # 1,048,576
73 | GB = float(KB ** 3) # 1,073,741,824
74 | TB = float(KB ** 4) # 1,099,511,627,776
75 |
76 | if B < KB:
77 | return '{0} {1}'.format(B, 'Bytes' if 0 == B > 1 else 'Byte')
78 | elif KB <= B < MB:
79 | return '{0:.2f} KB'.format(B / KB)
80 | elif MB <= B < GB:
81 | return '{0:.2f} MB'.format(B / MB)
82 | elif GB <= B < TB:
83 | return '{0:.2f} GB'.format(B / GB)
84 | elif TB <= B:
85 | return '{0:.2f} TB'.format(B / TB)
86 |
87 |
88 | def resource_path(relative_path):
89 | # noinspection PyProtectedMember
90 | return join(sys._MEIPASS, relative_path) if hasattr(sys, '_MEIPASS') else relative_path
91 |
92 |
93 | def copyfile_safe(input_file_path, target_file_dir, file_name):
94 | if not exists(target_file_dir):
95 | makedirs(target_file_dir)
96 |
97 | target_file_path = target_file_dir + file_name
98 | if exists(target_file_path):
99 | print_warn(
100 | 'we will not copy file[%s] because of there is a another file with the same name has been handled.' % input_file_path)
101 | else:
102 | copyfile(input_file_path, target_file_dir + file_name)
103 |
--------------------------------------------------------------------------------
/README-zh.md:
--------------------------------------------------------------------------------
1 | # Webp转换与扫描
2 |
3 | 
4 | 
5 | 
6 | [](https://github.com/Jacksgong/webp-converter)
7 | [](https://github.com/Jacksgong/webp-converter/blob/master/README-zh.md)
8 | [](https://pypi.python.org/pypi/webp-converter)
9 |
10 | Webp批量定向转换与结果分析工具。
11 |
12 | 
13 |
14 | ## 目的
15 |
16 | 1. 批量转换PNG/JPG到Webp文件
17 | 2. 自动忽略转换以后会变大的图片(会拷贝原图到`[output-directory]/origin/`目录)
18 | 3. 自动忽略转换失败的图片(会拷贝原图到`[output-directory]/failed/`目录)
19 | 4. 如果你需要可以通过参数`--ignore-transparency-image: true`来不转换带有透明像素点的图片(会拷贝原图到`[output-directory]/transparency`目录)
20 | 5. 输出转换结果,转换完后输出结果
21 | 6. 如果你需要可以通过参数`--r`来自动用转换后的webp替换原图
22 |
23 | ## 安装
24 |
25 | ```shell
26 | brew install webp
27 | pip install webp-converter
28 | ```
29 |
30 | ## 使用
31 |
32 | 
33 |
34 | #### 案例
35 |
36 | 如果你想要转换当前目录下的所有图片并且转换以后图片会变小的情况下,转换后的图片 **直接替换** 原来的图片:
37 |
38 | ```shell
39 | webpc --r
40 | ```
41 |
42 | 
43 |
44 | 如果你想要转换当前目录下的所有图片,使用`70`的 **质量**,并且 **输出** 目录指定在`~/Downloads/test-converted` 当转换后的图片会变小的情况下:
45 |
46 | ```shell
47 | webpc -q=70 -o=~/Downloads/test-converted/
48 | ```
49 |
50 | 
51 |
52 | 如果你想要转换当前目录下的所有图片,并且 **清除** `webp-converted`目录下的所有内容,并且将 **质量** 指定为 `95`,并且 **输出** 目录指定为 `./webp-converted`,并且 **忽略存在透明度的图片**,在转换后会变小的情况下:
53 |
54 | ```shell
55 | webpc --c --ignore-transparency-image -q=95
56 | ```
57 | 
58 |
59 | 如果你想要转换过程中忽略一些包含特殊字符的文件,可以通过`--ignore-filename-match`来做到,以下案例就是忽略文件名包含`.9`的文件:
60 |
61 | ```shell
62 | webpc --r --ignore-filename-match='.9'
63 | ```
64 |
65 | 如果你想要转换所有 **存储在** `~/Downloads/img/test`中的图片,并且 **输出** 目录指定为 `~/Downloads/test-converted`,并且仅仅转换在输出目录中 **不存在** 的图片,在转换后会变小的情况下:
66 |
67 | ```shell
68 | webpc -o=~/Downloads/test-converted/ ~/Downloads/img/test
69 | ```
70 |
71 | 
72 |
73 | ## 我的终端的风格配置
74 |
75 | 如果你想要适配和上面截图一样的终端风格,非常简单:
76 |
77 | - 首先,请使用[powerlevel9k](https://github.com/bhilburn/powerlevel9k)主题(正如Powerlevel9k文档提到的安装Powerlevel9k主题,并且安装Powerline字体).
78 | - 其次,请配置[iTerm2-Neutron](https://github.com/Ch4s3/iTerm2-Neutron)色系.
79 | - 最后, 请配置ini的shell(如果你使用的是zsh,只需要添加下列代码到`~/.zshrc`文件中):
80 | ```
81 | POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(dir vcs)
82 | POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status time)
83 | POWERLEVEL9K_TIME_FORMAT="%D{%H:%M:%S}"
84 | POWERLEVEL9K_NODE_VERSION_BACKGROUND='022'
85 | POWERLEVEL9K_SHORTEN_DIR_LENGTH=2
86 | ```
87 |
88 | ## License
89 |
90 | ```
91 | Copyright 2017, JacksGong(https://jacksgong.com)
92 |
93 | Licensed under the Apache License, Version 2.0 (the "License");
94 | you may not use this file except in compliance with the License.
95 | You may obtain a copy of the License at
96 |
97 | http://www.apache.org/licenses/LICENSE-2.0
98 |
99 | Unless required by applicable law or agreed to in writing, software
100 | distributed under the License is distributed on an "AS IS" BASIS,
101 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
102 | See the License for the specific language governing permissions and
103 | limitations under the License.
104 | ```
105 |
--------------------------------------------------------------------------------
/webpc/converter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python -u
2 |
3 | """
4 | Copyright 2017, JacksGong(https://jacksgong.com)
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | """
18 | import subprocess
19 | import os
20 | from os import remove, rename
21 | from os.path import exists
22 |
23 | from webpc.helper import size_diff, print_process, resource_path
24 |
25 | RESULT_SUCCESS = 0
26 | RESULT_FAILED = -1
27 | RESULT_WEBP_LARGER = -2
28 | RESULT_WITH_TRANSPARENCY = -3
29 | RESULT_ALREADY_EXIST = -4
30 |
31 | FNULL = open(os.devnull, 'w')
32 |
33 |
34 | class Converter:
35 | swap_webp_path = None
36 | command_prefix = list()
37 |
38 | def __init__(self, swap_webp_path, quality_ratio):
39 | self.swap_webp_path = swap_webp_path
40 |
41 | command = list()
42 | command.append(resource_path("cwebp"))
43 | # command_prefix = '%s ' % resource_path('cwebp')
44 | if quality_ratio >= 100:
45 | command.append("-lossless")
46 | command.extend(['-q', '100'])
47 | # command_prefix += '-lossless -q 100 '
48 | else:
49 | command.extend(['-q', quality_ratio.__str__()])
50 | # command_prefix += '-q ' + quality_ratio.__str__() + ' '
51 |
52 | self.command_prefix = command
53 |
54 | def convert(self, ignore_transparency_img, image_file_path, image_file_name, webp_file_path, is_debug):
55 | # whether has already converted
56 | if exists(webp_file_path):
57 | # has already converted!
58 | _reduce_size = size_diff(image_file_path, webp_file_path)
59 |
60 | if _reduce_size < 0:
61 | remove(webp_file_path)
62 | print_process(
63 | image_file_name + ' has already converted, but it larger than origin-image: ' + _reduce_size.__str__() + ' so, remove it and re-convert it!')
64 | else:
65 | print_process(image_file_name + ' has already converted! reduce: ' + _reduce_size.__str__())
66 | return RESULT_ALREADY_EXIST, _reduce_size
67 |
68 | # transparency
69 | if ignore_transparency_img and image_file_name.endswith('.png'):
70 | from PIL import Image
71 |
72 | try:
73 | img = Image.open(image_file_path, 'r')
74 | except IOError:
75 | print_process("NOT convert " + image_file_name + ' because convert failed!')
76 | return RESULT_FAILED, 0
77 |
78 | if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
79 | alpha = img.convert('RGBA').split()[-1]
80 | for pixel in alpha.getdata():
81 | if pixel < 255:
82 | print_process(
83 | 'NOT convert ' + image_file_name + ' because there is alpha[' + pixel.__str__() + ']')
84 | return RESULT_WITH_TRANSPARENCY, 0
85 |
86 | print_process('convert for ' + image_file_path)
87 |
88 | swap_webp_path = self.swap_webp_path
89 |
90 | command = list(self.command_prefix)
91 | command.append(image_file_path)
92 | command.extend(['-o', swap_webp_path])
93 |
94 | if is_debug:
95 | subprocess.Popen(command).communicate()
96 | print(command.__str__())
97 | else:
98 | subprocess.Popen(command, stdout=FNULL, stderr=subprocess.STDOUT).communicate()
99 |
100 | # print command_prefix + image_file_path + ' -o ' + swap_webp_path
101 | # system(command_prefix + image_file_path + ' -o ' + swap_webp_path)
102 | # whether convert failed
103 | if not exists(swap_webp_path):
104 | # convert failed!
105 | print_process("NOT convert " + image_file_name + ' because convert failed!')
106 | return RESULT_FAILED, 0
107 |
108 | _reduce_size = size_diff(image_file_path, swap_webp_path)
109 | if _reduce_size <= 0:
110 | # invalid convert
111 | print_process(
112 | 'NOT convert ' + image_file_name + ' because the webp one is larger: ' + (-_reduce_size).__str__())
113 | remove(swap_webp_path)
114 | return RESULT_WEBP_LARGER, 0
115 |
116 | print_process('convert ' + image_file_name + ' and reduce size: ' + _reduce_size.__str__())
117 | rename(swap_webp_path, webp_file_path)
118 | if exists(swap_webp_path): remove(swap_webp_path)
119 | return RESULT_SUCCESS, _reduce_size
120 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Webp Converter and Analytics
2 |
3 | 
4 | 
5 | 
6 | [](https://github.com/Jacksgong/webp-converter)
7 | [](https://github.com/Jacksgong/webp-converter/blob/master/README-zh.md)
8 | [](https://pypi.python.org/pypi/webp-converter)
9 |
10 | An powerful webp batch converter and differ analytics tool.
11 |
12 | You can use this tool to converter batch images(png/jpg) to webp and output size changes.
13 |
14 | 
15 |
16 |
17 | ## Purpose
18 |
19 | 1. Convert batch images from PNG/JPG format to Webp format
20 | 2. WILL NOT convert images if its webp one is larger than origin one automatically(the origin one will be copied to `[output-directory]/origin/` directory)
21 | 3. WILL NOT convert images if it is failed to convert to webp one automatically(the origin image of failed one will be copied to `[output-directory]/failed` directory)
22 | 4. You can ignore all images which has transparency pixel if you want with `--ignore-transparency-image` config(the origin image of has-transparency-image will be copied to `/webp-converted/transparency` directory)
23 | 5. Output convert result, like how much size reduces, how many files skip convert, etc...
24 | 6. You can replace the images with converted-webp image automatically if you want with `replace: true` config
25 |
26 | ## Install
27 |
28 | ```shell
29 | brew install webp
30 | pip install webp-converter
31 | ```
32 |
33 | ## Use
34 |
35 | 
36 |
37 | #### Example
38 |
39 | If you just want to convert all images on the current files when it can be smaller after converted and **replace** the origin one:
40 |
41 | ```shell
42 | webpc --r
43 | ```
44 |
45 | 
46 |
47 |
48 | If you just want to convert all images on the current folder and with **quality-ratio** to `70` and **output** to `~/Downloads/test-converted` when it can be smaller after converted:
49 |
50 | ```shell
51 | webpc -q=70 -o=~/Downloads/test-converted/
52 | ```
53 |
54 | 
55 |
56 |
57 | If you just want to convert all images on the current folder and with **clean** the `webp-converted` folder if it exist and with **quality-ratio** to `95` and **output** to `./webp-converted` and **ignore images when it has transparency** on it when it can be smaller after converted:
58 |
59 | ```shell
60 | webpc --c --ignore-transparency-image -q=95
61 | ```
62 | 
63 |
64 | If you want to convert ignore filename contain the sepcial word, you can use `--ignore-filename-match`, the following demo is skip convert all files which name contains '.9':
65 |
66 | ```shell
67 | webpc --r --ignore-filename-match='.9'
68 | ```
69 |
70 | If you want to convert all **images on** `~/Downloads/img/test` folder and **output** converted result to `~/Downloads/test-converted` folder and only converted origin images when it isn't has **same name** `.webp` file on `~/Downloads/test-converted` folder(just not with `--c` argument) when it can be smaller after converted:
71 |
72 |
73 | ```shell
74 | webpc -o=~/Downloads/test-converted/ ~/Downloads/img/test
75 | ```
76 |
77 | 
78 |
79 | ## My Terminal Config
80 |
81 | If you want to adapter the same theme like screenshot above, it's very easy:
82 |
83 | - Firstly, please use [powerlevel9k](https://github.com/bhilburn/powerlevel9k) theme(Install the Powerlevel9k Theme and Powerline Fonts as the powerlevel9k repo readme doc said).
84 | - Secondly, please config the [iTerm2-Neutron](https://github.com/Ch4s3/iTerm2-Neutron) color scheme.
85 | - Thirdly, please config your shell(If you are using zsh, just add following code to the `~/.zshrc` file):
86 | ```
87 | POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(dir vcs)
88 | POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status time)
89 | POWERLEVEL9K_TIME_FORMAT="%D{%H:%M:%S}"
90 | POWERLEVEL9K_NODE_VERSION_BACKGROUND='022'
91 | POWERLEVEL9K_SHORTEN_DIR_LENGTH=2
92 | ```
93 |
94 | ## License
95 |
96 | ```
97 | Copyright 2017, JacksGong(https://jacksgong.com)
98 | Licensed under the Apache License, Version 2.0 (the "License");
99 | you may not use this file except in compliance with the License.
100 | You may obtain a copy of the License at
101 | http://www.apache.org/licenses/LICENSE-2.0
102 | Unless required by applicable law or agreed to in writing, software
103 | distributed under the License is distributed on an "AS IS" BASIS,
104 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
105 | See the License for the specific language governing permissions and
106 | limitations under the License.
107 | ```
108 |
--------------------------------------------------------------------------------
/webpc/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python -u
2 |
3 | """
4 | Copyright 2017, JacksGong(https://jacksgong.com)
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | """
18 | import argparse
19 | import os
20 | import time
21 | from os import makedirs, remove
22 | from os.path import exists, join
23 | from shutil import rmtree
24 | from sys import exit
25 |
26 | from webpc.converter import Converter, RESULT_ALREADY_EXIST, RESULT_FAILED, RESULT_WEBP_LARGER, RESULT_WITH_TRANSPARENCY
27 | from webpc.helper import print_blue, resource_path, colorize, CYAN, GREEN, human_bytes, copyfile_safe, handle_home_case, \
28 | print_warn
29 |
30 | __version__ = '4.1.0'
31 | __author__ = 'JacksGong'
32 |
33 | print("-------------------------------------------------------")
34 | print(" Webp Converter v" + __version__)
35 | print("")
36 | print("Thanks for using okcat! Now, the doc is available on: ")
37 | print_blue(" https://github.com/Jacksgong/webp-converter")
38 | print("")
39 | print(" Have Fun!")
40 | print("-------------------------------------------------------")
41 |
42 |
43 | def main():
44 | default_output_directory = "%s/%s" % (os.getcwd(), 'webp-converted/')
45 | parser = argparse.ArgumentParser(description='Converter and analytics batch of images(png/jpg) to webp')
46 | parser.add_argument('image_directory', nargs='*', default=[os.getcwd()], help='Origin images directory path')
47 | parser.add_argument('-q', '--quality-ratio', dest='quality_ratio', type=int, default=100,
48 | help='Quality ratio, between 0 to 100, 100 is lossless, 0 is highest compression ratio, default value is 100')
49 | parser.add_argument('-o', '--output-directory', dest='output_directory',
50 | default=default_output_directory,
51 | help='the output directory of converted path, default value is ./webp-converted/')
52 | parser.add_argument('--ignore-transparency-image', dest='ignore_transparency_image', action='store_true',
53 | help='Whether need to ignore images which has transparency pixel on it, default value is false')
54 | parser.add_argument('--r', dest='replace_origin', action='store_true',
55 | help='Whether replace the origin images files directly or not, default value is false')
56 | parser.add_argument('--c', dest='clear_env', action='store_true',
57 | help='Whether need to clean the output directory before convert images, default value is false')
58 | parser.add_argument('--debug', dest='debug', action='store_true',
59 | help='Whether need to print debug message, default value is false')
60 | parser.add_argument('--ignore-filename-match', dest='ignore_filename_match', default='',
61 | help='ignore file when the name contain the provide value(such as .9)')
62 |
63 | args = parser.parse_args()
64 |
65 | start_time = time.time()
66 |
67 | input_directory = handle_home_case(args.image_directory[0])
68 | output_directory = handle_home_case(args.output_directory)
69 | quality_ratio = args.quality_ratio
70 | ignore_transparency_image = args.ignore_transparency_image
71 | replace_origin = args.replace_origin
72 | clean_env = args.clear_env
73 | is_debug = args.debug
74 | ignore_filename_match = args.ignore_filename_match
75 |
76 | if replace_origin and (clean_env or output_directory != default_output_directory):
77 | exit(
78 | "the --c and -o can't company with --r, because of --r means you need to store the converted images on the origin "
79 | "images directory and replace the origin images directly, and -o is means you want to store the converted images "
80 | "on some different directory, and --c is means you want to clear the output directory you provided with -o before"
81 | " convert.")
82 |
83 | if replace_origin:
84 | print('origin images will be replace with webp images on ' + input_directory)
85 | else:
86 | print('origin images on ' + input_directory + ' will be converted to ' + output_directory)
87 |
88 | command_prefix = '%s ' % resource_path('cwebp')
89 | if quality_ratio >= 100:
90 | command_prefix += '-lossless -q 100 '
91 | else:
92 | command_prefix += '-q ' + quality_ratio.__str__() + ' '
93 |
94 | keep_origin_path = output_directory + 'origin/'
95 | convert_fail_path = output_directory + 'failed/'
96 | transparency_image_path = output_directory + 'transparency/'
97 | swap_webp_path = join(output_directory, 'swap.webp') if not replace_origin else join(input_directory, 'swap.webp')
98 |
99 | if clean_env and exists(output_directory):
100 | rmtree(output_directory)
101 | print("clear all env on " + output_directory)
102 |
103 | if not replace_origin and not exists(output_directory):
104 | makedirs(output_directory)
105 |
106 | if exists(swap_webp_path):
107 | remove(swap_webp_path)
108 |
109 | output_data = OutputData()
110 | try:
111 | loop(
112 | input_directory=input_directory,
113 | output_directory=output_directory,
114 | swap_webp_path=swap_webp_path,
115 | transparency_image_path=transparency_image_path,
116 | quality_ratio=quality_ratio,
117 | convert_fail_path=convert_fail_path,
118 | keep_origin_path=keep_origin_path,
119 | ignore_transparency_image=ignore_transparency_image,
120 | is_debug=is_debug,
121 | replace_origin=replace_origin,
122 | output_data=output_data,
123 | ignore_filename_match=ignore_filename_match
124 | )
125 | except KeyboardInterrupt:
126 | print('')
127 | print('INTERRUPT BY USER.')
128 | if exists(swap_webp_path):
129 | remove(swap_webp_path)
130 | pass
131 |
132 | output_data.dump(
133 | replace_origin=replace_origin,
134 | input_directory=input_directory,
135 | output_directory=output_directory,
136 | start_time=start_time,
137 | ignore_filename_match=ignore_filename_match
138 | )
139 |
140 |
141 | class OutputData:
142 | all_reduce_size = 0
143 | valid_convert_file_count = 0
144 | failed_convert_count = 0
145 | scan_file_count = 0
146 | skip_file_count = 0
147 | skip_transparency_file_count = 0
148 | skip_ignore_match_name_file_count = 0
149 |
150 | def __init__(self):
151 | pass
152 |
153 | def dump(self, replace_origin, input_directory, output_directory, start_time, ignore_filename_match):
154 | print('-----------------------------------------------')
155 | print(' ')
156 | if replace_origin:
157 | colorize('Replace %s image files on %s' % (self.valid_convert_file_count, input_directory),
158 | fg=CYAN)
159 | else:
160 | print(get_result('All files handled on: ', output_directory, fg=CYAN))
161 |
162 | print(get_result('Consume: ', (time.time() - start_time), _format='%s%.3fs', fg=CYAN))
163 | print(' ')
164 | print(get_result('Scan files count: ', self.scan_file_count))
165 | print(get_result('Converted files count: ', self.valid_convert_file_count))
166 | print(get_result('Reduce size: ', human_bytes(self.all_reduce_size)))
167 | print(get_result('Skip files(because convert failed) count: ', self.failed_convert_count))
168 | print(get_result('Skip files(because the webp one is greater than origin one) count: ', self.skip_file_count))
169 | if self.skip_transparency_file_count > 0:
170 | print(get_result('Skip files(because there is transparency) count: ', self.skip_transparency_file_count))
171 | if self.skip_ignore_match_name_file_count > 0:
172 | print(get_result('Skip files(because their name contain %s) count: ' % ignore_filename_match,
173 | self.skip_ignore_match_name_file_count))
174 | print (' ')
175 | print ('-----------------------------------------------')
176 |
177 |
178 | def get_result(title, message, _format='%s%s', fg=GREEN):
179 | return _format % (colorize(title, fg=fg), message)
180 |
181 |
182 | def loop(input_directory, output_directory, swap_webp_path, transparency_image_path, quality_ratio, convert_fail_path,
183 | keep_origin_path, ignore_transparency_image, is_debug,
184 | replace_origin, output_data, ignore_filename_match):
185 | handler = Converter(swap_webp_path, quality_ratio)
186 | for subdir, dirs, files in os.walk(input_directory):
187 | for file_name in files:
188 | if file_name == '.DS_Store':
189 | continue
190 | if ignore_filename_match != '' and file_name.__contains__(ignore_filename_match):
191 | if is_debug:
192 | print('ignore %s because it contain %s' % (file_name, ignore_filename_match))
193 | output_data.skip_ignore_match_name_file_count += 1
194 | continue
195 | if not file_name.endswith('.jpg') and not file_name.endswith('.png'):
196 | continue
197 |
198 | if output_directory in subdir:
199 | continue
200 |
201 | output_data.scan_file_count += 1
202 | input_file_path = join(subdir, file_name)
203 | output_file_name = file_name.rsplit('.', 1)[0] + '.webp'
204 | if replace_origin:
205 | output_file_path = join(subdir, output_file_name)
206 | else:
207 | output_file_path = join(output_directory, output_file_name)
208 |
209 | result, reduce_size = handler.convert(ignore_transparency_image, input_file_path, file_name,
210 | output_file_path, is_debug)
211 | if reduce_size > 0:
212 | output_data.all_reduce_size += reduce_size
213 | if result != RESULT_ALREADY_EXIST:
214 | output_data.valid_convert_file_count += 1
215 | elif result == RESULT_FAILED:
216 | output_data.failed_convert_count += 1
217 | elif result == RESULT_WEBP_LARGER:
218 | output_data.skip_file_count += 1
219 | elif result == RESULT_WITH_TRANSPARENCY:
220 | output_data.skip_transparency_file_count += 1
221 |
222 | if replace_origin:
223 | if reduce_size > 0:
224 | remove(input_file_path)
225 | else:
226 | if result == RESULT_WITH_TRANSPARENCY:
227 | copyfile_safe(input_file_path, transparency_image_path, file_name)
228 | elif result == RESULT_FAILED:
229 | copyfile_safe(input_file_path, convert_fail_path, file_name)
230 | elif result == RESULT_WEBP_LARGER:
231 | copyfile_safe(input_file_path, keep_origin_path, file_name)
232 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2017 JacksGong(https://jacksgong.com)
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------