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

为测试Untiy工程里Texture的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     
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值