使用python脚本实现iOS图片资源压缩

最近,该公司有了新的要求,要精简代码。这个博客记录了如何压缩图片。

[En]

Recently, the company has a new requirement to slim down the code. This blog records how to compress pictures.

原则:

[En]

Principle:

编写一个脚本,遍历图片文件夹‘.xcsets’中的所有文件,然后使用第三方算法压缩图像并将其替换回来。

[En]

Write a script that traverses all the files in the picture folder ‘.xcassets’, and then uses a third-party algorithm to compress the images and replace them back.

结果:

[En]

Results:

使用python脚本实现iOS图片资源压缩

由于项目中的PNG图像已被压缩,这次只压缩了后缀为JGP的图片。由此可见,它仍然有效。

[En]

As the png images in the project have been compressed, this time only the pictures with the suffix jgp are compressed. It can be seen that it is still effective.

代码如下:

[En]

The code is as follows:

import os
import tinify
import shutil

tinify.key = '5J54hg59ysAuhHFPxXB*******'

source_file = '/Users/user/Desktop/Hotel.xcassets'
dest_file = '/Users/user/Desktop/destimages'

def getPngFileNames(source_dir):
    pngDicts = []
    for (parent, dirnames, filenames) in os.walk(source_dir):
        for filename in filenames:
            if filename.endswith('.jpg'):
                tempDict = {}
                tempDict['name'] = filename
                tempDict['path'] = os.path.join(parent, filename)
                pngDicts.append(tempDict)

    return pngDicts

def compressImages(uncompress_images):
    for pngDict in uncompress_images:
        source = tinify.from_file(pngDict['path'])
        source.to_file(os.path.join(dest_file, pngDict['name']))

def replace_file(new_path, old_path):
    pngs = getPngFileNames(source_file)
    for name in os.listdir(new_path):
        for pngDict in pngs:
            if pngDict['name'] == name:
                shutil.copyfile(os.path.join(new_path, name), pngDict['path'])

if __name__ == '__main__':
    replace_file(dest_file, source_file)
    # pngs = getPngFileNames(source_file)
    # compressImages(pngs)
    print('done')

Original: https://www.cnblogs.com/machao/p/9807016.html
Author: 马在路上
Title: 使用python脚本实现iOS图片资源压缩

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/6660/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

最近整理资源【免费获取】:   👉 程序员最新必读书单  | 👏 互联网各方向面试题下载 | ✌️计算机核心资源汇总