10 lines of Python code, batch compression of 500 pictures, is too powerful

Time:2019-10-23

10 lines of Python code, batch compression of 500 pictures, is too powerful

This article is original and first published on the public account [Python is a cat, without authorization, do not reprint.
The original address: https://mp.weixin.qq.com/s/5hpFDgjCpfb0O1Jg-ycACw

Readers familiar with “Python cat” should know that all of my posts use highly distinctive illustrations — cat for the original article and dog for the reproduced article, with rare exceptions.

These days, I’m building a personal website with Github page + hexo, and I want to migrate the photos and articles to keep the style. Here’s the problem: all the images I use are in high definition, which slows down the loading process. Therefore, you need to compress the image before uploading it.

I summarize the requirements as follows:

  • We need to compress the pictures in batches. There are about 200 pictures now, and we will add them later
  • Is compression, not cut interception, do not change the size of the picture
  • The original picture is mostly 10m-30m, and the goal is to compress it to within 1M, the smaller the better

According to these clues, I search “batch compression images”, “image compression tools”, “batch processing images”……

The initial idea was to find a lightweight image compression tool, a simple processing. However, whether the search was done in the wrong way or the information was filtered in the wrong way, the results were not very popular.

Find the tool has two types of local and online, but after test are not very ideal, only to find that after some software download is paid, some when use as a direct result of the program card dead, some compression ratio is not requiring multiple compression, some require the original image size no more than 5 M, some requirements the batch quantity does not exceed 20, some does not support batch compression… Group members also recommended PS+ batch, acdsee, and even snapseed, a mobile app.

After spending a lot of time, I came across an article about compressing images in Python. How did I not think of it?

Look at what others did first. This article, “how to batch compress images with Python intelligence?” (https://zhuanlan.zhihu.com/p/32246003), the article introduces the use of PIL library Image module to Image compression method, mainly by adjusting the Image width numerical approach.

PIL is a powerful image-processing library, but only supports Python 2 and has long since stopped updating. Developers have improved and maintained Pillow on top of it, supporting Python 3. I’ve heard it before. I’ve never used it. So brother cat looked up several tutorials and documents. After reading it found that the compression of the image is the main method of scale, crop and change format, not what I want.

Also saw an article, “how in the case of nondestructive make pictures smaller” (https://juejin.im/post/5959fbe0f265da6c2518d740), the article, it introduces the Yelp (the largest review websites) pictures of three kinds of optimization strategy: Pillow, dynamic tuning, replace the encoder. Some methods are very high, should be the industry advanced experience, but it wants to ensure that the picture lossless, all methods combined to reduce the average size of the picture by 30%, so does not meet my requirements. In addition, it introduced several methods, but it took time to study, and I gave up.

Finally, finally found a very convenient, and very satisfied program, the following began to enter the topic. (don’t be too long-winded, the exploration process is also very interesting) (SHH, actually, because the following method is so simple, only a few lines of code, I can’t help but force play… )

—————- — careful dividing line —————- ————

Tinypng, which offers an online image compression service, is one of the best of all image compression tools, but it has limitations: it can process up to 20 images in batches, and no more than 5 megabytes each.

10 lines of Python code, batch compression of 500 pictures, is too powerful

The site was conscientious enough to open up the free API, which removed the size limit on each page and limited it to 500 images per month. That’s more than enough for me.

Here’s how to use it. The first step is to register on its website to get the unique API_KEY. Use email registration, very simple.

Then install package:

pip install --upgrade tinify

10 lines of Python code, batch compression of 500 pictures, is too powerful

Next comes the image processing:

import tinify
import os

Tinify.key = 'fill in your key here'
Path = "C:\Users\ yunpoyue\Pictures\ cat" #

for dirpath, dirs, files in os.walk(path):
    for file in files:
        imgpath = os.path.join(dirpath, file)
        print("compressing ..."+ imgpath)
        tinify.from_file(imgpath).to_file(imgpath)

Less than 10 lines of code, easy to bulk compression pictures, simply not too cool! 20 M pictures can be compressed to 2 M, the compression rate reached an amazing 90%, the results are gratifying.

Its API also provides image clipping, watermarking, saving compressed images to cloud service providers (amazon cloud, Google cloud) and other functions, very powerful. Except that the compression process is a bit slow.

After some exploration and comparison, I am sure this is the best solution at present, so I strongly share it with you.

10 lines of Python code, batch compression of 500 pictures, is too powerful

The public,”Python is a cat], this serial series of high quality articles, cat philosophy cat series, Python advanced series, good book recommendation series, technical writing, high quality English recommendation and translation, and so on, welcome to pay attention. Background reply”The love of learning“And get a free study package.