python工具(1) — 图片的位深度压缩

来源:互联网 发布:网络电子赌博的危害 编辑:程序博客网 时间:2024/06/07 08:10

在游戏开发项目中,图片资源是最多的、占用空间也是最大的,因此我们需要降低图片的占用空间,我们用开源的软件pngquant来实现将32bit图片压缩为8bit的图片,关于pngquant,请戳:pngquant官网 , 我们只需要下载它的.exe文件就可以。


接下来是去python官网下载PIL(Python Image Library),因为我们需要它来检测png图片的格式。

准备好这些后,就可以写一个python脚本来实现了:


import osimport os.pathimport Image# Please reset the root directory Path !ImageFilePath = "E:\Resources"def getFilesAbsolutelyPath(ImageFilePath):    currentfiles = os.listdir(ImageFilePath)    filesVector = []    for file_name in currentfiles:        fullPath = os.path.join(ImageFilePath, file_name)        if os.path.isdir(fullPath):            newfiles = getFilesAbsolutelyPath(fullPath)            filesVector.extend(newfiles)        else:            filesVector.append(fullPath)    return filesVectorfilePathVector = getFilesAbsolutelyPath(ImageFilePath)pngFile = []for filename in filePathVector:    flag = filename.find(".png")    if flag != -1:        im = Image.open(filename)        if im.mode != "P":            pngFile.append(filename)             print(mode)# pngquant.exe pathpngquantPath = "E:\Resources\pngquant.exe -f --ext .png --quality 50-80 "#get .Png File Namefor filename in pngFile:os.system(pngquantPath + filename)


os.listdir(path),返回值是个list,存放了当前path目录下所有的文件/文件夹,os.path.join(path, file_name)会将当前的文件/文件名前面添加path根目录名,从而使文件名的路径为绝对路径; 然后通过os.path.isdir(fullpath)判断当前的file_name是否为一个目录,如果是目录,则递归处理它,最后得到的newfiles即为该目录下所有的文件名。

获取到所有的png文件后,需要判断文件当前是否经过pngquant处理了,im = Image.open(filename),打开文件后,im携带了文件的信息,im.mode值为一个str,如果png文件已经经过了pngquant处理,那么它的mode值为"P",否则为"RGBA", 我们将未处理过的图片保存到一个list中。

最后使用pngquant.exe来处理这些图片,pngquant参数如下:




-f 参数代表的意思为: overwrite existing output files,改写已经存在的文件,即我们需要将处理后的图片覆盖原来的图片。

--ext .png表示图片处理后的扩展名为.png

--quality 50-80 表示图片的质量最低为原来的50%,低于这个值将会出错。


我们用 E:\Resources\pngquant.exe -f --ext .png --quality 50-80 filename来处理每一个文件。

关于mode,PIL官网上这么写的:

1 (1-bit pixels, black and white, stored with one pixel per byte)L (8-bit pixels, black and white)P (8-bit pixels, mapped to any other mode using a colour palette)RGB (3x8-bit pixels, true colour)RGBA (4x8-bit pixels, true colour with transparency mask)CMYK (4x8-bit pixels, colour separation)YCbCr (3x8-bit pixels, colour video format)I (32-bit signed integer pixels)F (32-bit floating point pixels

我们从美术那里得到的原始的png图片为32bit的RGBA图片,含有Alpha通道掩码值,经pngquant压缩后成为8bit的P图片,P表示的是,8位像素,用到调色板因此可以映射到其他任意的mode,所以此时它类似于一个查色表,可以映射到其他任意模式。



1 0
原创粉丝点击