Python advanced recursively obtains all pictures with the specified suffix name in the specified folder, and compresses the file size of all the specified pictures correspondingly

Python advanced recursively obtains all pictures with the specified suffix name in the specified folder, and compresses the file size of all the specified pictures correspondingly

Table of contents

Python advanced recursively obtains all pictures with the specified suffix name in the specified folder, and compresses the file size of all the specified pictures correspondingly

1. Brief introduction

Second, the realization principle

3. Matters needing attention

4. Effect preview

5. Implementation steps

6. Key code


1. Brief introduction

Python is a cross-platform computer programming language. It is an object-oriented dynamically typed language, originally designed for writing automation scripts (shells), and with the continuous updating of versions and the addition of new features of the language, the more it is used for the development of independent, large-scale projects. Python is an interpreted scripting language that can be used in the following fields: Web and Internet development, scientific computing and statistics, artificial intelligence, education, desktop interface development, software development, back-end development, web crawling.

Here is an introduction to recursively obtaining all files in the specified folder, and compressing the size of the specified type of image files. Here, imgae in Pillow is used to compress jpg and png type images. Here is a brief introduction. The method is not unique. For a better method, please leave a message to add.

Operating environment:

  • 1、win 10
  • 2、python 3.8
  • 3、pycharm 2022.1.3
     

Second, the realization principle

1. os.listdir reads all the files in the folder, if it is the file os.path.isfile, and it is a picture file of the specified jpg and png suffix type, and compresses the corresponding picture

2. If it is a folder, it can be processed recursively in the first step

3. Use from PIL import Image, Image for image compression

3. Matters needing attention

1. Since python 3.8, the Pillow plugin is installed in the environment, and Pillow contains PIL

2. Set the image compression quality according to your needs

4. Effect preview

1. The corresponding file size before uncompressed

 2. Corresponding file size after compression

 

 

5. Implementation steps

1. Prepare environment folders and pictures, add 1 folder under TestImageFolder folder, 2.txt, img1.jpg and img2.png, and then 1 folder, add img1.jpg and img2.png

 

2. First, implement recursive reading of the files in the folder, mainly related to os.listdir

2. Next, image.open opens the image, and save compresses and saves it.

 

3. Filter and compress image files with the suffix jpg and png

 

4. Specify the image folder, you can recursively compress the image, and the compression result is as follows

6. Key code

import os
from PIL import Image


def recursiveGetFilesFromFolder(folderPath, fileHandler):
    """
    递归获取文件夹下的文件,并做对应处理
    :param folderPath: 文件夹路径
    :param fileHandler: 对文件的处理函数
    :return:
    """
    pathDir = os.listdir(folderPath)
    print("pathDir = ", pathDir)
    for fileOrDir in pathDir:
        fileOrDirPath = os.path.join('%s\%s' % (folderPath, fileOrDir))
        print("fileOrDirPath = " + fileOrDirPath)
        if os.path.isfile(fileOrDirPath):
            if fileHandler:
                fileHandler(fileOrDirPath)
            continue
        # 是文件夹,则递归处理
        recursiveGetFilesFromFolder(fileOrDirPath, fileHandler)


def compressImageFile(filePath, quality):
    """
    进行图片文件压缩处理
    :param filePath: 文件路径
    :param quality: 压缩图片质量 1-100
    :return:
    """
    im = Image.open(filePath)
    # quality 是设置压缩比
    im.save(filePath, quality=quality)
    im.close()


def handleImageFile(filePath):
    """
    处理 jpg png 后缀的文件
    :param filePath:文件路径
    :return:
    """
    if filePath.endswith(".jpg") or filePath.endswith(".png"):
        compressImageFile(filePath, 20)


def test():
    recursiveGetFilesFromFolder(r'E:\Study\z_tmp\TestImageFolder', handleImageFile)


if __name__ == '__main__':
    test()

Guess you like

Origin blog.csdn.net/u014361280/article/details/125965751