前言
对于Android APP来说,apk包的大小是需要严格控制,过大的安装包会导致用户放弃下载你的app,而对于包体的优化分为很多方面,今天这篇文章主要是通过把项目的图片资源转换为webp格式,来缩小包的体积。
语言:python
注意:因为用到了webp环境,此代码仅可以运行在mac上。
原理
使用mac的webp环境,执行终端的转换命令。
cwebp -q 100 originalImage.png -o newImage.webp
步骤
安装webp环境
Mac 可以使用homebrew来安装实用程序。
brew install webp
安装实用程序完成后,就可以使用 cwebp命令 将 JPEG 或 PNG 图像转换成 webp 格式, 也可以通过dwebp 命令将 webp 图像转换回 PNG、PAM、PPM 或 PGM 图像。
示例
cwebp [options] -q quality input.jpg -o output.webp
质量选项应该是 0 (差)到 100 (很好)之间的数字,典型的质量值大约是 80,也可以多尝试几个数值。本人一般转图片时质量用的是80
dwebp input_file.webp [options] [-o output_file]
python代码
import os
import os.path
import time
遍历想要转换的图片所在的文件夹,深度遍历
# 深度遍历,完整路径,文件类型
def get_filename(path,filetype):
name =[]
final_name = []
for root,dirs,files in os.walk(path):
for i in files:
if filetype in i:
# 排除点9图片
if '.9' in i:
continue
wholePath = root +'/'+ i.replace(filetype,'')
#生成不带完整路径的文件名组成的列表
name.append(wholePath)
#生成filetype后缀的文件名组成的列表
final_name = [item +filetype for item in name]
print('找到%d个可以转换的图片' % len(final_name))
return final_name
开始转换
def png2webp():
path = input('输入想要遍历的文件夹:(默认./images)')
filetype = input('想要转换的图片格式(png、jpg,默认png):')
q = input('转换质量(0~100,默认100):')
deleteFlag = input('转换完成后是否删除原图片(Y/n,默认n):')
startFlag = input('开始执行(Y/n):')
if path.strip() == '':
path = './images'
if filetype.strip() == '':
filetype = 'png'
if q.strip() == '':
q = '100'
if deleteFlag.strip() == '':
deleteFlag = 'n'
if startFlag.strip() == '':
startFlag = 'n'
if not startFlag.lower() == 'y':
print('执行终止')
return
files = get_filename(path, '.'+filetype)
for file in files:
print('\033[1;33m>>>>>>>>>开始转换%s\033[0m' % file)
wholepath = file
resultpath = file.replace('.'+filetype, '.webp')
# 终端输入是有结果的,不知道为什么在python看不到结果,干脆不获取了
os.popen('cwebp -q %s %s -o %s' % (q, wholepath, resultpath))
print('\033[1;33m%s转换完成<<<<<<<<<\033[0m' % resultpath)
print('全部完成,一共转换了%d张图片' % len(files))
if deleteFlag.lower() == 'y':
print('休息3秒后开始删除')
time.sleep(3)
for file in files:
os.remove(file)
print('\033[1;33m>>>>>>>>>%s删除完成<<<<<<<<<\033[0m' % file)
开始执行
png2webp()
可以直接对项目的res文件夹执行,转换项目里面的图片格式。
转换后的效果