使用python指令碼實現iOS圖片資源壓縮
阿新 • • 發佈:2018-11-11
最近公司有一個新的需求,要把程式碼進行瘦身,這篇部落格記錄下如何對圖片進行壓縮的。
原理:
寫一個指令碼,把圖片資料夾'.xcassets'的所有檔案遍歷出來,然後使用一個第三方的演算法把圖片壓縮後再替換回去
成果:
由於在該工程中的png圖片已經壓縮過了,這次只壓縮了jgp為字尾的圖片,可以看出,還是有效果的
程式碼如下:
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')