TexturePacker批處理python

TexturePacker版本 4.2.1

前言:因爲水平有限,錯誤再所難免,望指正, 大家如果有購買能力的話,希望購買TexturePacker正版,不要再用盜版了。好東西就應該支持。

1.安裝TexturePacker Command Line Tool

1.1 Mac下安裝 TexturePacker => Install Command Line Tool => Install


1.2 win下安裝 必須配置環境變量。

2.TexturePacker命令說明(主要命令)

2.1 --texture-format

  --texture-format <id>         Sets the format for the textures.
                                The format type is automatically derived from the sheet's file name
                                if possible.
                                Available formats:
                                    png               PNG (32bit)
                                    png8              PNG (8bit indexed)
                                    pvr3              PowerVR Texture Format, PVR Version 3
                                    pvr3gz            PowerVR Texture Format, PVR Version 3, compressed with gzip
                                    pvr3ccz           PowerVR Texture Format, PVR Version 3, compressed with zlib, cocos2d header
                                    jpg               JPG image format, lossy compression, no transparency
                                    bmp               24 bit BMP
                                    tga               Targa Image Format
                                    tiff              Tagged Image File Format
                                    pkm               PKM image format, ETC1 compression
                                    webp              WebP lossless / lossy format
                                    atf               Adobe Texture Format
                                    pvr2              PowerVR Texture Format, PVR Version 2, deprecated
                                    pvr2gz            PowerVR Texture Format, PVR Version 2, compressed with gzip, deprecated
                                    pvr2ccz           PowerVR Texture Format, PVR Version 2, compressed with zlib, cocos2d header, deprecate
紋理輸出格式,常用的 png,png8,pvr3ccz,pkm,jpg。  

png全平臺都適用, 

png8文件小但效果比起png來說有一些損失,並且對一些圖片漸變處理效果損失更加明顯,如果效果看不過去還是用png吧

pvr3ccz pvr3ccz是pvr2ccz升級版,添加了一些功能,可以使用其他像素格式比如 ETC1,pvr2ccz 以前是不支持的。

pkm 主要用於ETC1
jpg 由於沒有alpha通道,所以常用於背景圖,壓縮到80%的效果和原圖差距不大,但壓縮比例很嚇人,文件小效果好,目前背景沒有alpha通道的就用的這個。由於在cocos2d 2.x版本上加載速度慢,並且消耗內存大,根據實際情況選用。

2.2 --opt 像素格式

--opt <pixelformat>           Optimized output for given pixel formats. Supported formats are:
                                    RGBA8888           32bit, 8bit/channel, 8bit transparency
                                    BGRA8888           32bit, 8bit/channel, 8bit transparency
                                    RGBA4444           16bit, 4bit/channel, 4bit transparency
                                    RGB888             24bit, 8bit/channel, no transparency
                                    RGB565             16bit, 5bit red, 6bit green, 5bit blue, no transparancy
                                    RGBA5551           16bit, 5bit/channel, 1bit transparancy
                                    RGBA5555           20bit, 5bit/channel, 5bit transparancy
                                    PVRTCI_2BPP_RGB    PVRTC compression, 2bit per pixel
                                    PVRTCI_4BPP_RGB    PVRTC compression, 4bit per pixel
                                    PVRTCI_2BPP_RGBA   PVRTC compression, 2bit per pixel
                                    PVRTCI_4BPP_RGBA   PVRTC compression, 4bit per pixel
                                    PVRTCII_2BPP       PVRTC2 compression, 2bit per pixel
                                    PVRTCII_4BPP       PVRTC2 compression, 4bit per pixel
                                    ALPHA              8bit transparency
                                    ALPHA_INTENSITY    8bit intensity, 8bit transparency
                                    ETC1_RGB           ETC1 compression
                                    ETC1_A             ETC1 Alpha channel only
                                    ETC1_RGB_A         ETC1 RGB + ETC1 Alpha
                                    ETC2_RGB           ETC2 compression
                                    ETC2_RGBA          ETC2 Alpha
                                    DXT1               Compressed with DXT1, 1 bit transparency
                                    DXT5               Compressed with DXT5, transparency
                                    ATF_RGB            ETC1+DXT1+PVRTC4, no transparency
                                    ATF_RGBA           ETC1/ETC1+DXT5+PVRTC4, no transparency
像素格式常用 RGBA8888,RGBA4444,RGB888,RGB565,RGBA5551,RGBA5555,PVRTCI_4BPP_RGBA,ETC1_RGB,ERC1_A。

RGBA8888 效果最好消耗內存比較大。 內存消耗32bpp

RGBA4444 效果比起RGBA8888在某些圖片上丟失得有點大。 但消耗內存是 RGBA8888的一半。 內存消耗16bpp

RGB888 少個alpha通道,內存佔用是 RGBA8888 的 四分之三。內存消耗24bpp

RGB565 效果上比 RGB888差一些,但對於有些圖片還是可以接受的, 但沒有alpha通道。內存消耗16bpp

RGBA5551 對於透明漸變少的可以採用效果 比 RGBA4444好。內存消耗16bpp

RGBA5555 alpha通道增加 自然透明效果好了,但內存消耗也增加了。 仙存消耗24bpp

PVRTCI_4BPP_RGBA 效果上比RGBA8888要差一些,但內存消耗極小,加載速度也快,渲染速度快,在ios上完全是可以接受的,強烈建議ios 用這個格式。內存消耗4bpp

ETC1_RGB 消耗內存極小,加載速度比RGBA8888快,渲染速度快,效果也比較不錯,但沒有alpha通道,這也是ETC1被一直吐槽的點,所以後來有個ETC2。內存消耗4bpp

ETC1_A 和ETC1_RGB 組合在一起用,給ETC1_RGB提供alpha通道,達到透明效果,建議android可以選用這種方法來處理ETC1沒有alpha通道的缺點。內存消耗4bpp

ETC1_RGB、ETC1_A可以通過shader對紋理進行兩次採集處理達到RGBA的效果,這裏就不討論這個問題了。


內存消耗計算方式 :假如一張圖是 1024 * 888

ETC1內存消耗 = 1024 * 888 * 4bpp / 8 = 454656byte = 444KB

PVRTCI_4BPP_RGBA內存消耗 = 1024 * 888 * 4bpp / 8 = 454656byte = 444KB

RGB888內存消耗 = 1024 * 888 * 24bpp / 8 = 2727936byte = 2664KB

RGBA8888內存消耗 = 1024 * 888 * 32bpp / 8 = 3637248byte = 3552KB

RGBA4444內存消耗 = 1024 * 888 * 16bpp / 8 = 1818624byte = 1776KB

2.3 --data 輸出紋理文件的信息數據路徑 plist

  --data <filename>             Name of the data file to write

2.4 --sheet 輸出圖集路徑

  --sheet <filename>            Name of the sheet to write, see texture-format for formats available

2.5 --dither-type 顏色抖動

  --dither-type <dithertype>    Dithering to improve quality of color reduced images
                                    NearestNeighbour      no dithering
                                    Linear                no dithering
                                    FloydSteinberg        Floyd Steinberg, no alpha
                                    FloydSteinbergAlpha   Floyd Steinberg, with alpha
                                    Atkinson              Atkinson, no alpha
                                    AtkinsonAlpha         Atkinson, alpha
                                    PngQuantLow           PNG-8 only: minimum dithering
                                    PngQuantMedium        PNG-8 only: medium dithering
                                    PngQuantHigh          PNG-8 only: strong dithering

對圖片顏色進行一些插值處理。不同參數算法不同。 

PngQuantLow,PngQuantMedium,PngQuantHigh選用PNG8 可以試試這三個參數。用了比原PNG8好 

2.6 --format
--format <format>             Format to write, default is cocos2d
                                Available formats:
                                    2dtoolkit           2D Toolkit exporter
                                    andengine           Format for AndEngine
                                    agk                 Format for AppGameKit
                                    batterytech         BatteryTech Exporter
                                    bhive               Format for BHive
                                    caat                Exporter for CAAT - the Canvas Advanced Animation Toolkit
                                    cegui               Format for CEGUI / OGRE
                                    cocos2d             plist format version 3 for cocos2d
                                    cocos2d-v2          old plist format version 2 for cocos2d (deprecated)
                                    cocos2d-x           plist format version 3 for cocos2d-x with polygon packing
                                    corona-imagesheet   Exporter for Corona(TM) SDK using new image sheet format.
                                    css                 css format for web design
                                    easeljs             Exporter for EaselJS.
                                    gideros             Format for Gideros
                                    json-array          Text file for json/html as array
                                    json                Text file for json/html as hash
                                    kwik                Exporter for Kwik using new image sheet format.
                                    less                Creates a LESS file that can be incorporated into a sprites arrangement
                                    libgdx              text file for lib GDX
                                    libRocket           Exporter to demonstrate how to crate your own exporters
                                    melonjs             Data file for MelonJS
                                    moai                Format for Moai
                                    molecule            Exporter for Molecule Framework
                                    monogame            Input format for the MonoGame TexturePacker Importer
                                    orx                 Orx Exporter
                                    panda               Exporter for Panda Engine
                                    phaser-json-array   JSON array data for Phaser
                                    phaser-json-hash    JSON hash data for Phaser
                                    pixijs              Data file for PixiJS
                                    sass-mixins         Exporter for SASS.
                                    shiva3d-jpsprite    Shiva3D with JPSprite extension
                                    shiva3d             Exporter for Shiva3D.
                                    slick2d             Format for Slick2D
                                    sparrow             xml file for Sparrow/Starling SDK
                                    spine               text file for Spine
                                    spritesheet-only    Exports only the sprite sheet without data file
                                    spritekit           plist format for SpriteKit, Objective-C header file
                                    spritekit-swift     plist format for SpriteKit, with swift class file
                                    spriter             JSON file for Spriter
                                    spritestudio        OPTPiX SpriteStudio 5 CellMap File.
                                    tresensa            Exporter for TreSensa TGE.
                                    uikit               Exporter for UIKit
                                    unity               Text file for Unity(R), json format with .txt ending
                                    unity-texture2d     Input format for the Unity(R) TexturePacker Importer
                                    unreal-paper2d      Format for UnrealEngine / Paper2d
                                    vplay               JSON file for V-Play engine
                                    wave-engine-1       WaveEngine Sprite Sheet
                                    x2d                 Export to x2d engine format.
                                    xml                 Generic XML format
                                    plain               Exporter to demonstrate how to crate your own exporters
紋理打包方式

cocos2d-x 新版本的多邊形打包方式,目前cocos studio 不支持

cocos2d-v2 老版本的打包方式,現在已經被廢棄,但我還是用的這個。

cocos2d 新版本的打包方式 目前cocos studio 不支持

其他方式比如unity,unreal,spritekit如果有用的可以自行研究


2.7 --multipack 多圖集打包

--multipack                   Create multiple sprite sheets if not all sprites match into a single one
避免一個圖集包含不完所以精靈,開起則會生成多張圖集。但要在 --data --sheet 加入 {n}  索引會從0開始

2.8 --maxrects-heuristics

    MaxRects
      --maxrects-heuristics     Heuristic for MaxRects algorithm
                                    Best              Best
                                    ShortSideFit      ShortSideFit
                                    LongSideFit       LongSideFit
                                    AreaFit           AreaFit
                                    BottomLeft        BottomLeft
                                    ContactPoint      ContactPoint

maxrect的算法方式


2.9 --enable-rotation 精靈旋轉

--enable-rotation             Enables rotation of sprites (overriding file format's defaults)
開起旋轉,得到更小的圖集


2.10 --trim-mode 透明像素處理

  --trim-mode <value>           Remove transparent parts of a sprite to shrink atlas size and speed up rendering
                                    None              Keep transparent pixels
                                    Trim              Remove transparent pixels, use original size.
                                    Crop              Remove transparent pixels, use trimmed size, flush position.
                                    CropKeepPos       Remove transparent pixels, use trimmed size, keep position.
                                    Polygon           Approximate sprite contour with polygon path.

常用Trim。

Trim 刪除圖片透明像素,用原圖片像素大小,在幀動畫中常用,

None 保證原樣大小,和透明像素。 不建議用。圖集大。

Crop 刪除圖片透明像素,用刪除後的圖片像素大小,位置改變

CropKeepPos 刪除圖片透明像素,用刪除後的圖片像素大小,位置不變

Polygon 多邊形方式,得到圖集更小,目前cocos2d 也不支持多邊形精靈。


建議使用Trim,其他用處不大。

2.11 --basic-sort-by 和 --basic-order 

    Basic
      --basic-sort-by           Sort order for the sprite list
                                    Best              Best
                                    Name              Name
                                    Width             Width
                                    Height            Height
                                    Area              Area
                                    Circumference     Circumference
      --basic-order             Sorting direction
                                    Ascending         Ascending
                                    Descending        Descending

選用 Name 和 Ascending就行了。這個我覺得不用多做了解,按名稱升序方式排序在 list中

2.12 --max-size 最大紋理圖集大小

--max-size <int>              Sets the maximum width and height for the texture in auto size mode, default is 2048

建議使用2048,最大不超過4096,各個機型支持圖集大小有區別。 以前

2.13 --size-constraints 圖集高寬約束方式

  --size-constraints <value>    Restrict sizes
                                    POT               Power of 2 (2,4,8,16,32,...)
                                    WordAligned       Texture width is multiple of 2 (for 16-bit formats)
                                    AnySize           Any size
POT 2次冪方式

AnySize 任意大小

2.14  --force-publish

--force-publish               Ignore smart update hash and force re-publishing of the files

強制重新再次生成,忽略智能更新,廢棄以前的 --smart-update

2.15 --shape-padding 和 --border-padding

  --shape-padding <int>         Sets a padding around each shape, value is in pixels, default is 2
  --border-padding <int>        Sets a padding around each the border, value is in pixels, default is 2

--shape-padding 邊框填充像素

--border-padding 相當於精靈之間的間距像素


2.16  --scale 和 --scale-mode精靈縮放

  --scale <float>               Scales all images before creating the sheet. E.g. use 0.5 for half size
  --scale-mode <mode>           Use mode for scaling:
                                    Smooth            Smooth
                                    Fast              Fast (Nearest Neighbor)
                                    Scale2x           Scale2x (fixed 2x upscaling)
                                    Scale3x           Scale3x (fixed 3x upscaling)
                                    Scale4x           Scale4x (fixed 4x upscaling)
                                    Eagle             Eagle2x (fixed 2x upscaling)
                                    Hq2x              Hq2x (fixed 2x upscaling)

主要用於不同 分辨率的機型和處理紋理大小,如果只用一套資源來適配。不用關心。scale 設爲1就行

2.17  --replace 正則表達式

  --replace <regexp>=<string>   Replaces matching parts of the sprite's name with <string>
                                Uses full regular expressions, make sure to escape the expression
正則表達式來修改精靈名,--replace ^={sheetName}_ win和mac得到的結果不一樣。

3. python 批處理

目錄結構


#!/usr/bin/python  
#encoding=utf-8  
import io
import os
import sys  
import hashlib  
import string  
import re




rootPath = os.path.abspath(os.path.join(sys.argv[0], os.pardir))

# # input paths
ImageDir= os.path.join(rootPath, "input")

# temporary path to place the sprite sheets
OutputDir = os.path.join(rootPath, "output")

#PVRTC4
OutputDirPVRTC4 = os.path.join(OutputDir, "PVRTC4") #ios 中PVRTC4輸出目錄
#ETC
OutputDirETC =  os.path.join(OutputDir, "ETC") #android 中 ETC輸出目錄
#PNG
OutputDirPNG =  os.path.join(OutputDir, "PNG") #通用 中 PNG輸出目錄

OutputDirPNG8 =  os.path.join(OutputDir, "PNG8") #通用 中 PNG輸出目錄

# # path of the texture packer command line tool
TP="TexturePacker"


print("ImageDir = " + ImageDir)
print("OutputDir = " + OutputDir)
print("OutputDirPVRTC4 = " + OutputDirPVRTC4)
print("OutputDirETC = " + OutputDirETC)
print("OutputDirPNG = " + OutputDirPNG)
print("OutputDirPNG8 = " + OutputDirPNG8)
print("TP = " + TP)


#文件輸出目錄
def createPath(cPath):
    if not os.path.isdir(cPath):
        os.mkdir(cPath)


# --trim-sprite-names  去除png等後綴
# --multipack 多圖片打包開起,避免資源圖太多,生成圖集包含不完全,開起則會生成多張圖集。
# --maxrects-heuristics macrect的算法  參數 Best ShortSideFit LongSideFit AreaFit BottomLeft ContactPoint
# --enable-rotation 開起旋轉,計算rect時如果旋轉將會使用更優的算法來處理,得到更小的圖集
# --border-padding 精靈之間的間距
# --shape-padding 精靈形狀填充
# --trim-mode Trim 刪除透明像素,大下使用原始大小。 參數 None Trim Crop CropKeepPos Polygon
# --basic-sort-by Name  按名稱排序
# --basic-order Ascending 升序
# --texture-format 紋理格式
# --data 輸出紋理文件的信息數據路徑 plist
# --sheet 輸出圖集路徑 png
# --scale 1 縮放比例 主要用於低分辨率的機子多資源適配。
# --max-size 最大圖片像素 一般我是用的2048,超過2048以前的有些android機型不支持。
# --size-constraints 結紋理進行大小格式化,AnySize 任何大小 POT 使用2次冪 WordAligned
# --replace 正則表達式,用於修改plist加載後的名稱
# --pvr-quality PVRTC 紋理質量
# --force-squared 強制使用方形
# --etc1-quality ETC 紋理質量
def pack_textures(inputPath, outputPath, opt, scale, maxSize, sheetSuffix, textureFormat, sizeConstraints, sheetName, otherParams, fileNameSuffix):
    packCommand = TP + \
        " --multipack" \
        " --format cocos2d-v2" \
        " --maxrects-heuristics best" \
        " --enable-rotation" \
        " --shape-padding 2" \
        " --border-padding 0" \
        " --trim-mode Trim" \
        " --basic-sort-by Name" \
        " --basic-order Ascending" \
        " --texture-format {textureFormat}" \
        " --data {outputSheetNamePath}{fileNameSuffix}.plist" \
        " --sheet {outputSheetNamePath}{fileNameSuffix}.{sheetSuffix}" \
        " --scale {scale}" \
        " --max-size {maxSize}" \
        " --opt {opt}" \
        " --size-constraints {sizeConstraints}" \
        " {inputPath}" \
        " {otherParams}"


    # win 和 mac 上處理正則表達式結果不一樣
    if sys.platform == "win32":
        packCommand = packCommand + " --replace (.png)$=" \
            " --replace \\b={sheetName}_" \
            " --replace {sheetName}_$=.png"
    else:
        packCommand = packCommand + " --replace ^={sheetName}_"


    packCommand = packCommand.format(
        textureFormat=textureFormat,
        outputSheetNamePath=os.path.join(outputPath,sheetName) + "_{n}",
        sheetName=sheetName,
        sheetSuffix=sheetSuffix,
        scale=scale,
        maxSize=maxSize,
        opt=opt,
        sizeConstraints=sizeConstraints,
        inputPath=inputPath,
        otherParams=otherParams,
        fileNameSuffix=fileNameSuffix)
    os.system(packCommand)

if __name__ == '__main__':
    createPath(OutputDir)
    createPath(OutputDirPVRTC4)
    createPath(OutputDirETC)
    createPath(OutputDirPNG)
    createPath(OutputDirPNG8)
    for sheet in os.listdir(ImageDir):
        iPath = os.path.join(ImageDir, sheet)
        if os.path.isdir(iPath): 
            pack_textures(iPath,OutputDirPVRTC4,'PVRTCI_4BPP_RGBA',1,2048,'pvr.ccz',"pvr3ccz","POT",sheet,"--pvr-quality best --force-squared", "")
            pack_textures(iPath,OutputDirETC,'ETC1_RGB',1,2048,'pkm',"pkm","AnySize",sheet,"--etc1-quality high-perceptual", "")
            pack_textures(iPath,OutputDirETC,'ETC1_A',1,2048,'pkm',"pkm","AnySize",sheet,"--etc1-quality high-perceptual", "_alpha")
            pack_textures(iPath,OutputDirPNG,'RGBA8888',1,2048,'png',"png","AnySize",sheet,"--png-opt-level 7", "")
            pack_textures(iPath,OutputDirPNG8,'RGBA8888',1,2048,'png',"png8","AnySize",sheet,"--png-opt-level 7 --dither-type PngQuantHigh", "")








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章