【Unity工具】使用python修改图片尺寸宽高为4的倍数
1.unity中图片的宽高不是4的倍数,使用ETC2格式时候不能压缩
2.图片的设置

3.使用python的PIL库批量修改图片尺寸
根据操作系统和python版本下载对应PIL

下载完成之后,在下载文件的文件夹中打开pip安装PIL的whl
1 | pip3 install Pillow-8.0.1-cp37-cp37m-macosx_10_10_x86_64.whl |
在python中import PIL,没有报错的话就是安装成功了
1 2 | python import PIL |
4.将想要修改的图片放在一个文件夹中,把下面py代码放在同一个文件夹中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import os from PIL import Image import struct ''' 检查并调整bg图片的宽高,确保宽高都是4的倍数,这样才可以使用ETC压缩格式 ''' #遍历目录中的png文件 def list_pic(dirpath): print (dirpath) for root, dirs, fs in os.walk(dirpath): for f in fs: if f.endswith( '.jpg' ) or f.endswith( '.png' ): yield os.path.join(root, f) #获取图片实际尺寸 def get_png_size(fpath): with open (fpath, 'rb' ) as f: f.seek( 4 * 4 , 0 ) return (struct.unpack( ">II" , f.read( 8 )) ) def getSize(path): img = Image. open (path) imgSize = img.size #大小/尺寸 w = img.width #图片的宽 h = img.height #图片的高 f = img. format #图像格式 return w,h #列出宽高不是4的倍数的图片 def list_not_4_pic(dirpath): for f in list_pic(dirpath): w,h = getSize(f) print (f + "---" + str (w) + "---" + str (h)) if w % 4 ! = 0 or h % 4 ! = 0 : yield f #调整图片的尺寸,确保宽高是4的倍数 def resize_4_pic(dirpath): with open ( 'resize_4_pic.output.log' , 'w' ) as log: for f in list_not_4_pic(dirpath): img = Image. open (f) (w,h) = img.size nw = (w % 4 = = 0 ) and w or (w + ( 4 - (w % 4 ))) nh = (h % 4 = = 0 ) and h or (h + ( 4 - (h % 4 ))) print ( (w, h), '->' ,(nw,nh), f) log.write( "%s | (%d,%d)-> (%d,%d)\n" % (f,w, h,nw,nh)) img = img.resize( (nw,nh), Image.ANTIALIAS) img.save(f) if '__main__' = = __name__: resize_4_pic( '.' ) |
5.执行python脚本,修改图片尺寸并保存
1 | python resize_pic.py |
标签:
工具类
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?