python pngquant batch compress png images

  1. Use pngquant to compress all pictures in a folder or compress pictures in all first-level subfolders in a folder
  2. The resolution of the compressed image is adjusted to 0.5 times of the original (adjust according to your own situation)
  3. Calculate the image size, compression rate and compression time before and after compression

Since pngquant cannot compress the resolution, it may still be relatively large after pngquant is compressed, so add the Pillow library to compress the resolution again in the compress_resize function.

The pngquant_resize_1() function compresses all png images in the first-level subfolder under the specified path, and the new compressed images overwrite the source files.
The pngquant_resize_2() function inputs the source folder and the target folder to compress all the pictures in the source folder, and generates compressed pictures to the target folder

You need to install pngquant, put pngquant.exe in the Scripts folder under the python installation directory, and add the Scripts folder path to the environment variable.

Note:

  1. If there are subfolders in the folder that needs to be compressed, only the pictures in the subfolders will be compressed, and the pictures in the subfolders in the subfolders will not be compressed. You can change it yourself. If you want to traverse all subfolders For pictures, just use os.walk().
  2. I am using pngquant to compress images here, you need to enter pngquant --help in cmd to view the help documentation of pngquant
  3. Here, the size of the compressed image is calculated, the compression rate is calculated, and the time-consuming of the compression process is calculated, just to see the compression effect. If you don’t need it, you can delete these.
  4. The compressed png image. If it's jpg, I haven't tried it, and I feel that pngquant probably won't work.
  5. The bad news is that after compressing the picture, it is basically impossible to compress the picture and then use the compression software to make a compressed package. Therefore, those who need it need to carefully consider the quality of pngquant and the aspect ratio of resize when compressing. .

The code is here on github

Guess you like

Origin blog.csdn.net/weixin_50624398/article/details/128277274