最近公司有一個新的需求,要把代碼進行瘦身,這篇博客記錄下如何對圖片進行壓縮的。算法
原理:
寫一個腳本,把圖片文件夾'.xcassets'的全部文件遍歷出來,而後使用一個第三方的算法把圖片壓縮後再替換回去app
成果:
3d
因爲在該工程中的png圖片已經壓縮過了,此次只壓縮了jgp爲後綴的圖片,能夠看出,仍是有效果的code
代碼以下:blog
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')