Remove the Alpha channel of all images in the Unity project,

Source: Internet
Author: User

Remove the Alpha channel of all images in the Unity project,
To test the performance pressure of Texture Alpha in the Untiy project, we need to temporarily remove the Alpha channel of all images in the Unity project for testing and comparison. Here is a basic technique. When an image does not have an Alpha channel, it does not need to be processed. How can we determine whether the image has an Alpha channel? Unity does not have a direct interface. But you can do this: 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     }  


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.