Foreword
The webpage pictures on the webp format are more saving network traffic and storage space, but local pictures are generally PNG format, so consider using Python's Pillow library to convert PNG format pictures into webp formats.
need:
- You can call at any place in the system. This needs to be compiled into a binary program or a script and put it under the PATH environment variable
- Support specified picture file input directory. The default is current directory.
- Support specified picture file output directory. The defaults to the same level of the input file.
- Support specified picture compression quality. The default is 80. You need to check the parameters.
- Support concurrently compressing multiple picture files. The default is serial. The maximum number of complications of parameters is the core number of CPUs.
Code
From Pil Import Image
Import argparse
From Pathlib Import Path
From Import ThreadPoolexecutor
Import OS
From time import time
DEF PARSE_ARGS ():
"" "Analyze the command line parameters" "" ""
Parser = (description = "convert png to webp",
usage = "" "" "
# Direct execution, default to all PNG files in the current directory to the same level directory
python
# Save the conversion webp file in the Output directory
python -OUTPUT
# Convert a single PNG file, do not support the specified output directory when converting alone
python -f
# Conversion at the same time, -T specifies the maximum concurrent number, the default is 1, and the maximum must not exceed the CPU core number
python -t 2
# Specify the compression quality of the picture, the default is 80, the value range is [0, 100], the higher the value, the better the quality, the larger the quality
python -q 75
"" ")
Parser.add_argument (
"-i", type = str, default = (), help = "Path to the input png Image"
Cure
Parser.add_argument (
"-o", type = str, default = (), help = "Path to the output webp image"
Cure
Parser.add_argument ("-F", Type = Str, default = "", help = "Specific File Name")
Parser.add_argument ("-t", type = int, default = 1, help = "number of threads to use")
Parser.add_argument (
"-q", type = int, default = 80, help = "question of the output webp image"
Cure
Return Parser.parse_args ()
DEF Convert_png_to_webp (input_path: Path, Output_path: PATH, Quality = 80) -> None:
"" "
Convert png to webp
Args:
input_path (PATH): Enter the file path
OUTPUT_PATH (PATH): The output file path can be a directory or a path of a webp file
Quality (int, optional): Image compression quality. Defeade 80.
"" "
# If the quality is not between 0 and 100, set to 80
If Quality> 100 or Quality <0:
Print ("Quality Must be between 0 and 100, now set to 80")
Real_q = Quality If Quality <= 100 and Quality> 0 Else 80
# If the input file does not exist, print the error message and return
if not input_path.exist ():
Print (F "Input File {input_path} Not Found")
Return
# If the output directory is specified, try to create the output directory
if not output_path.exist () and output_path. ()! = ".Webp":
try:
OUTPUT_PATH.MKDIR (parents = true)
Except Excetion as E:
Print (e)
Print ("Failed to Create Output Directory")
Return
# If the output directory is specified, modify the output file name as the input file name, and modify the extended name .webp
if output_path. ()! = ".webp":
OUTPUT_PATH = OUTPUT_PATH / Input_path.with_suffix (". Webp"). name
start = time ()
try:
With (input_path) as IMG:
Print (
f "converting {input_path}, question = {real_q}, size: {input_path.stat (). st_size / 1024: .2f} kb"
Cure
(output_path, "webp", question = real_q)
Print (
F "Convert PNG2WEBP Successfully, Output File: {output_path.name}, size: {int (output_path.stat (). ST_SIZE) / 1024: .2F} kb, elapsed time: {tim e () -start: .2f} s "
Cure
Except Excetion as E:
Print (f "convert png2webp failed: {e}")
DEF MULTI_THREAD_CONVERT (MAX_WORKERS: Int, Input_path, OUTPUT_PATH, Quality) -> None::
"" "Paid PNG PNG is webp" "" "" ""
Print (F "Convert Png to Webp with Multi Threads, MAX_WORKERS: {Max_Worker}"))
p = PATH (Input_path)
OP = PATH (OUTPUT_PATH) if output_path! = () Else None
max_Workers = MAX_WORKERS if max_Worker
With ThreadPoolexecutor (MAX_WORKERS = MAX_WORKERS) as Executor:
for f in ("**/*. PNG"):
((
Convert_png_to_webp, f, op or f.with_suffix (". Webp"), Quality
Cure
def main ():
start = time ()
args = PARSE_ARGS ()
if not:
if> 1:
multi_thread_convert (,,,,)
else:
p = PATH ()
op = path () if! = () else none
for f in ("**/*. PNG"):
Convert_png_to_webp (f, op or f.with_suffix (". Webp"),),),),),),),
else:
p = PATH ()
convert_png_to_webp(p, p.with_suffix(".webp"), )
Print (F "Finished! Total Elapset Time: {Time () - Start: .2f} s")
if __Name__ == "__main__":
main (main ()
Compile
Because the pillow installed in the Python virtual environment, if you want to call this script in other locations, you think two ways:
- In addition, write a shell script, if it is Windows, write the PowerShell script, write the logic of the call in this script, and put this script to
PATH
Under the path of the environment variable. - Compiled into binary files, put the compiled binary files to
PATH
Under the environment variable. This is more convenient to send it to others so that others do not need to install the Python environment on the computer.
Herepyinstaller
Compile the program into binary files and compile them in the Python virtual environment to reduce the volume of binary files
- Create a virtual environment
python -m venv png2webp
- Activate the virtual environment
# linux
cd png2webp
source ./bin/activate
# windows powershell
cd png2webp
.\Scripts\activate
- Installation dependence
python -m pip install pillow pyinstaller
- Compile. Pay attention to modify the actual Python file path.
pyinstaller -F --clean .\
- The generated binary files are in the current directory
dist
Directory, place it to itPATH
Under environmental variables, if necessary, it can be renamed. - The test is called in other directory
png2webp --help
use
# Direct execution, default to all PNG files in the current directory to the same level directory
png2webp
# Save the conversion webp file in the Output directory
pNG2WEBP -OUTPUT
# Convert a single PNG file, do not support the specified output directory when converting alone
pNG2WEBP -F
# Conversion at the same time, -T specifies the maximum concurrent number, the default is 1, and the maximum must not exceed the CPU core number
png2webp -t 2
# Specify the compression quality of the picture, the default is 80, the value range is [0, 100], the higher the value, the better the quality, the larger the quality
png2webp -q 75