移除Unity工程里所有图片的Alpha通道

发表于2017-11-03
评论1 1.8k浏览
为测试Untiy工程里Texture的Alpha对性能的压力,需要临时移除Unity工程里所有图片的Alpha通道,做测试对比。考虑到有些人没有这方面经验,为此,这里给大家分享一个移除移除Unity工程里所有图片的Alpha通道基本的技巧,当图片不存在Alpha通道时,就不需要处理,如何判断图片是否存在Alpha通道呢,Unity不存在直接的接口。但可以这么干:

1. 
ti.textureFormat = TextureImporterFormat.AutomaticTruecolor;   
 AssetDatabase.ImportAsset(_relativeAssetPath);

2. 
static bool IsNoAlphaTexture(Texture2D texture)
    {
        return texture.format == TextureFormat.RGB24;
    }

代码如下:
using UnityEngine;  
using System.Collections;  
using System.Collections.Generic;  
using UnityEditor;  
using System.IO;  
using System.Reflection;
public class RemoveAlphaChanel
{
    [MenuItem("TextureTest/Remove Texture Alpha Chanel")]
    static void ModifyTextures()
    {
        Debug.Log("Start Removing Alpha Chanel.");    
        string[] paths = Directory.GetFiles(Application.dataPath, "*.*", SearchOption.AllDirectories);
        foreach (string path in paths)
        {
            if (!string.IsNullOrEmpty(path) && IsTextureFile(path))   //full name  
            {
                RemoveTextureAlphaChanel(path);
            }
        }
        AssetDatabase.Refresh();    //Refresh to ensure new generated RBA and Alpha textures shown in Unity as well as the meta file
        Debug.Log("Finish Removing Alpha Chanel.");
    }
    [MenuItem("TextureTest/LimitTextureSizeTo128")]
    static void LimitTextures()
    {
        Debug.Log("Start Limit Textures.");
        string[] paths = Directory.GetFiles(Application.dataPath, "*.*", SearchOption.AllDirectories);
        foreach (string path in paths)
        {
            if (!string.IsNullOrEmpty(path) && IsTextureFile(path))   //full name  
            {
                try
                {
                    string assetRelativePath = GetRelativeAssetPath(path);
                    ReImportAsset(assetRelativePath);
                    Debug.Log("Limit Texture: " + assetRelativePath);
                }
                catch
                {
                    Debug.LogError("ReImport Texture failed: " + GetRelativeAssetPath(path));
                }              
            }
        }
        AssetDatabase.Refresh();    //Refresh to ensure new generated RBA and Alpha textures shown in Unity as well as the meta file
        Debug.Log("Finish Limit Textures.");
    }
    #region process texture
    static void RemoveTextureAlphaChanel(string _texPath)
    {
        string assetRelativePath = GetRelativeAssetPath(_texPath);
        SetTextureReadableEx(assetRelativePath);    //set readable flag and set textureFormat TrueColor
        Texture2D sourcetex = Resources.LoadAssetAtPath(assetRelativePath, typeof(Texture2D)) as Texture2D;  //not just the textures under Resources file  
        if (!sourcetex)
        {
            Debug.LogError("Load Texture Failed : " + assetRelativePath);
            return;
        }
        if (IsNoAlphaTexture(sourcetex))
        {
            Debug.Log("pass. no Alpha texture: " + assetRelativePath);
            return;
        }
        #region Get origion Mipmap Setting
        TextureImporter ti = null;
        try
        {
            ti = (TextureImporter)TextureImporter.GetAtPath(assetRelativePath);
        }
        catch
        {
            Debug.LogError("Load Texture failed: " + assetRelativePath);
            return;
        }
        if (ti == null)
        {
            return;
        }             
        bool bGenerateMipMap = ti.mipmapEnabled;    //same with the texture import setting      
        #endregion
        Texture2D rgbTex = new Texture2D(sourcetex.width, sourcetex.height, TextureFormat.RGB24, bGenerateMipMap);
        rgbTex.SetPixels(sourcetex.GetPixels());      
        rgbTex.Apply();
        byte[] bytes = rgbTex.EncodeToPNG();
        File.WriteAllBytes(assetRelativePath, bytes);
        ReImportAsset(assetRelativePath, sourcetex.width, sourcetex.height);
        Debug.Log("Succeed Removing Alpha : " + assetRelativePath);
    }
    static bool IsNoAlphaTexture(Texture2D texture)
    {
        return texture.format == TextureFormat.RGB24;
    }
    static void SetTextureReadableEx(string _relativeAssetPath)    //set readable flag and set textureFormat TrueColor
    {
        TextureImporter ti = null;
        try
        {
           ti = (TextureImporter)TextureImporter.GetAtPath(_relativeAssetPath);
        }
        catch
        {
            Debug.LogError("Load Texture failed: " + _relativeAssetPath);
            return;
        }
        if (ti == null)
        {
            return;
        }       
        ti.isReadable = true;
        ti.textureFormat = TextureImporterFormat.AutomaticTruecolor;      //this is essential for departing Textures for ETC1. No compression format for following operation.
        AssetDatabase.ImportAsset(_relativeAssetPath);
    }
    static void ReImportAsset(string path)
    {
        TextureImporter importer = null;
        try
        {
            importer = (TextureImporter)TextureImporter.GetAtPath(path);
        }
        catch
        {
            Debug.LogError("Load Texture failed: " + path);
            return;
        }
        if (importer == null)
        {
            return;
        }
        importer.maxTextureSize = 128;
        importer.anisoLevel = 0;
        importer.isReadable = false;  //increase memory cost if readable is true
        importer.textureFormat = TextureImporterFormat.AutomaticCompressed;
        AssetDatabase.ImportAsset(path);
    }
    static void ReImportAsset(string path, int width, int height)
    {
        try
        {
            AssetDatabase.ImportAsset(path);
        }
        catch
        {
            Debug.LogError("Import Texture failed: " + path);
            return;
        }
        TextureImporter importer = null;
        try
        {
            importer = (TextureImporter)TextureImporter.GetAtPath(path);
        }
        catch
        {
            Debug.LogError("Load Texture failed: " + path);
            return;
        }
        if (importer == null)
        {
            return;
        }
        importer.maxTextureSize = Mathf.Max(width, height);
        importer.anisoLevel = 0;
        importer.isReadable = false;  //increase memory cost if readable is true
        importer.textureFormat = TextureImporterFormat.AutomaticCompressed;
        importer.textureType = TextureImporterType.Image;
        if (path.Contains("/UI/"))
        {
            importer.textureType = TextureImporterType.GUI;
        }
        AssetDatabase.ImportAsset(path);
    }
    #endregion  
    #region string or path helper  
    static bool IsTextureFile(string _path)  
    {  
        string path = _path.ToLower();  
        return path.EndsWith(".psd") || path.EndsWith(".tga") || path.EndsWith(".png") || path.EndsWith(".jpg") || path.EndsWith(".bmp") || path.EndsWith(".tif") || path.EndsWith(".gif");  
    }
    static string GetRelativeAssetPath(string _fullPath)  
    {  
        _fullPath = GetRightFormatPath(_fullPath);  
        int idx = _fullPath.IndexOf("Assets");  
        string assetRelativePath = _fullPath.Substring(idx);  
        return assetRelativePath;  
    }  
    static string GetRightFormatPath(string _path)  
    {  
        return _path.Replace("\\", "/");  
    }  
    static string GetFilePostfix(string _filepath)   //including '.' eg ".tga", ".png",  no".dds"  
    {  
        string postfix = "";  
        int idx = _filepath.LastIndexOf('.');  
        if (idx > 0 && idx < _filepath.Length)  
            postfix = _filepath.Substring(idx, _filepath.Length - idx);  
        return postfix;  
    }  
    #endregion     
}  

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引