「Python」PNG OR JPG Convert to WebP

PNG/JPG Convert to Webp(Python)

foreword

Regarding the advantages and principles of webp, I have seen an article by Tencent before. Introduction to the principle of WebP and the current status of Android support

The webp image format is compatible with Android 4.0. The online converter was used to convert webp before, but the efficiency was too slow. The leaflet was fine, and batch conversion was very painful, so I wrote a python script to Automatically convert png or jpg to webp in batches

Environment construction

  • webp environment

    Macs can use homebrew to install utilities.

      brew install webp
    

    Once the utility is installed, you can use the cwebp command to convert JPEG or PNG images to webp format, and the dwebp command to convert webp images back to PNG, PAM, PPM, or PGM images.

    Example

      cwebp [options] -q quality input.jpg -o output.webp  
    

    The quality option should be a number between 0 (poor) and 100 (very good), a typical quality value is around 80, but try a few more values. I usually use 80 for the quality when transferring pictures.

      dwebp input_file.webp [options] [-o output_file]
    
  • python environment

    Python is very popular now, and there are a lot of python environment setups on the Internet. Google it. If you want to learn python, I recommend Mr. Liao Xuefeng's tutorial, which is relatively easy to understand. Teacher Liao Xuefeng Python

demand analysis

After understanding the above cwebp command, just use python to do a simple encapsulation of cwebp. First of all, I want the quality to be configurable; in addition, I also want to have a default size configuration. For example, if I change the folder below 20kb, I want to use the original image instead of converting it to webp and paste the code directly below. The big idea is this: first check the parameters, folder path, etc., output to the original folder _webp by default, copy and delete the original file after the conversion

# encoding=utf-8

#  -s 最小要压缩图片大小 (kb)
#  -i 要压缩的图片文件夹目录
#  -q 压缩图片质量  默认80

import commands
import os
import sys
import getopt
import shutil

input_file = "" 
quality = "80"

outputPath = input_file + "_webp"

compressSize = ""


def handle_sys_arguments():
    opts, args = getopt.getopt(sys.argv[1:], "hi:o:q:s:")
    global quality
    global output_file
    global compressSize
    global input_file

    for op, value in opts:
        # print("op:" + op + "__" + value)
        if op == "-i":
            input_file = value
        elif op == "-o":
            output_file = value
        elif op == "-h":
            print(" -s 最小要压缩图片大小 (kb)\n -i 要压缩的图片文件夹目录\n -q 压缩图片质量  默认80")
            exit()
        elif op == "-q":
            quality = value
        elif op == "-s":
            compressSize = value


def path_file(path):
    for i in os.listdir(path):
        print(i)
        new_path = os.path.join(path, i)
        if os.path.isfile(new_path):
            transform(new_path)
        else:
            path_file(new_path)


def transform(f):
    split_name = os.path.splitext(f)
    filePath = f

    print(split_name[0])

    if split_name[1] == ".webp" or (split_name[1] != ".jpg" and split_name[1] != ".png"):
        return

    if compressSize.strip() != "" and os.path.getsize(filePath) / 1024.0 > int(compressSize):
        command = "cwebp -q " + quality + " " + filePath + " -o " + \
                  split_name[0] + ".webp"
        commands.getstatusoutput(command)
        print("执行了:" + command)
    elif compressSize.strip() == "":
        command = "cwebp -q " + quality + " " + filePath + " -o " + \
                  split_name[0] + ".webp"
        commands.getstatusoutput(command)
        print("执行了:" + command)
    else:
        print("不压缩")


def check_args():
    if input_file.strip() == "":
        print("请输入要转换的文件夹路径")
        exit()


def copy_webp_files(sourceDir, targetDir):
    if not os.path.exists(targetDir):
        os.makedirs(targetDir)

    print sourceDir
    print(targetDir)

    for file in os.listdir(sourceDir):

        new_source_path = os.path.join(sourceDir, file)
        new_target_path = os.path.join(targetDir, file)

        # print("copyWebpFiles" + new_source_path)
        # print("copyWebpFiles_target" + new_target_path)

        if os.path.isdir(new_source_path):

            copy_webp_files(new_source_path, new_target_path)

        else:
            splite_name = os.path.splitext(file)
            print("copyWebpFiles_split" + splite_name[1])

            if splite_name[1] != ".webp":  # 只复制webp文件
                continue

            shutil.copy(new_source_path, new_target_path)
            os.remove(new_source_path)


if __name__ == '__main__':
    handle_sys_arguments()
    check_args()
    path_file(input_file)
    copy_webp_files(input_file, outputPath)

Example

I created a folder on the desktop and put some pictures that need to be captured and replaced. I need to convert all these pictures to webp and enter the command

python /Users/work/Desktop/webp_converter.py  -i /Users/work/Desktop/img

Webp

WebP-Converter

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324457871&siteId=291194637