[Unity]将所有 TGA、TIFF、PSD 和 BMP(可自定义)纹理转换为 PNG,以减小项目大小,而不会在 Unity 中造成任何质量损失

news2024/9/28 19:26:03

如何使用
只需在“项目”窗口中创建一个名为“编辑器”的文件夹,然后在其中添加此脚本即可。然后,打开窗口-Convert Textures to PNG,配置参数并点击“Convert to PNG! ”。

就我而言,它已将某些 3D 资源的总文件大小从 1.08 GB 减少到 510 MB。

只要禁用“Keep Original Files”或将项目的资源序列化模式设置为“强制文本”,就会保留对转换后的纹理的引用。
在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;

public class ConvertTexturesToPNG : EditorWindow
{
	private const string DUMMY_TEXTURE_PATH = "Assets/convert_dummyy_texturee.png";
	private const bool REMOVE_MATTE_FROM_PSD_BY_DEFAULT = true;

	private readonly GUIContent[] maxTextureSizeStrings = { new GUIContent( "32" ), new GUIContent( "64" ), new GUIContent( "128" ), new GUIContent( "256" ), new GUIContent( "512" ), new GUIContent( "1024" ), new GUIContent( "2048" ), new GUIContent( "4096" ), new GUIContent( "8192" ), new GUIContent( "16384" ) };
	private readonly int[] maxTextureSizeValues = { 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384 };

	private readonly GUIContent rootPathContent = new GUIContent( "Root Path:", "Textures inside this folder (recursive) will be converted" );
	private readonly GUIContent textureExtensionsContent = new GUIContent( "Textures to Convert:", "Only Textures with these extensions will be converted (';' separated)" );
	private readonly GUIContent excludedDirectoriesContent = new GUIContent( "Excluded Directories:", "Textures inside these directories won't be converted (';' separated)" );
	private readonly GUIContent keepOriginalFilesContent = new GUIContent( "Keep Original Files:", "If selected, original Texture files won't be deleted after the conversion" );
	private readonly GUIContent maxTextureSizeContent = new GUIContent( "Max Texture Size:", "Textures larger than this size will be downscaled to this size" );
	private readonly GUIContent optiPNGPathContent = new GUIContent( "OptiPNG Path (Optional):", "If 'optipng.exe' is selected, it will be used to reduce the image sizes even further (roughly 20%) but the process will take more time" );
	private readonly GUIContent optiPNGOptimizationContent = new GUIContent( "OptiPNG Optimization:", "Determines how many trials OptiPNG will do to optimize the image sizes. As this value increases, computation time will increase exponentially" );
	private readonly GUIContent optiPNGURL = new GUIContent( "...", "http://optipng.sourceforge.net/" );
	private readonly GUILayoutOption GL_WIDTH_25 = GUILayout.Width( 25f );

	private string rootPath = "";
	private string textureExtensions = ".tga;.psd;.tiff;.tif;.bmp";
	private string excludedDirectories = "";
	private bool keepOriginalFiles = false;
	private int maxTextureSize = 8192;
	private string optiPNGPath = "";
	private int optiPNGOptimization = 3;

	private Vector2 scrollPos;

	[MenuItem( "Window/Convert Textures to PNG" )]
	private static void Init()
	{
		ConvertTexturesToPNG window = GetWindow<ConvertTexturesToPNG>();
		window.titleContent = new GUIContent( "Convert to PNG" );
		window.minSize = new Vector2( 285f, 160f );
		window.Show();
	}

	private void OnEnable()
	{
		// By default, Root Path points to this project's Assets folder
		if( string.IsNullOrEmpty( rootPath ) )
			rootPath = Application.dataPath;
	}

	private void OnGUI()
	{
		scrollPos = GUILayout.BeginScrollView( scrollPos );

		rootPath = PathField( rootPathContent, rootPath, true, "Choose target directory" );
		textureExtensions = EditorGUILayout.TextField( textureExtensionsContent, textureExtensions );
		excludedDirectories = EditorGUILayout.TextField( excludedDirectoriesContent, excludedDirectories );
		keepOriginalFiles = EditorGUILayout.Toggle( keepOriginalFilesContent, keepOriginalFiles );
		maxTextureSize = EditorGUILayout.IntPopup( maxTextureSizeContent, maxTextureSize, maxTextureSizeStrings, maxTextureSizeValues );
		optiPNGPath = PathField( optiPNGPathContent, optiPNGPath, false, "Choose optipng.exe path", optiPNGURL );
		if( !string.IsNullOrEmpty( optiPNGPath ) )
		{
			EditorGUI.indentLevel++;
			optiPNGOptimization = EditorGUILayout.IntSlider( optiPNGOptimizationContent, optiPNGOptimization, 2, 7 );
			EditorGUI.indentLevel--;
		}

		EditorGUILayout.Space();

		// Convert Textures to PNG
		if( GUILayout.Button( "Convert to PNG!" ) )
		{
			double startTime = EditorApplication.timeSinceStartup;

			List<string> convertedPaths = new List<string>( 128 );
			long originalTotalSize = 0L, convertedTotalSize = 0L, convertedTotalSizeOptiPNG = 0L;

			try
			{
				rootPath = rootPath.Trim();
				excludedDirectories = excludedDirectories.Trim();
				textureExtensions = textureExtensions.ToLowerInvariant().Replace( ".png", "" ).Trim();
				optiPNGPath = optiPNGPath.Trim();

				if( rootPath.Length == 0 )
					rootPath = Application.dataPath;

				if( optiPNGPath.Length > 0 && !File.Exists( optiPNGPath ) )
					Debug.LogWarning( "OptiPNG doesn't exist at path: " + optiPNGPath );

				string[] paths = FindTexturesToConvert();
				string pathsLengthStr = paths.Length.ToString();
				float progressMultiplier = paths.Length > 0 ? ( 1f / paths.Length ) : 1f;

				CreateDummyTexture(); // Dummy Texture is used while reading Textures' pixels

				for( int i = 0; i < paths.Length; i++ )
				{
					if( EditorUtility.DisplayCancelableProgressBar( "Please wait...", string.Concat( "Converting: ", ( i + 1 ).ToString(), "/", pathsLengthStr ), ( i + 1 ) * progressMultiplier ) )
						throw new Exception( "Conversion aborted" );

					string pngFile = Path.ChangeExtension( paths[i], ".png" );
					string pngMetaFile = pngFile + ".meta";
					string originalMetaFile = paths[i] + ".meta";

					bool isPSDImage = Path.GetExtension( paths[i] ).ToLowerInvariant() == ".psd";

					// Make sure to respect PSD assets' "Remove Matte (PSD)" option
					if( isPSDImage )
					{
						bool removeMatte = REMOVE_MATTE_FROM_PSD_BY_DEFAULT;

						if( File.Exists( originalMetaFile ) )
						{
							const string removeMatteOption = "pSDRemoveMatte: ";

							string metaContents = File.ReadAllText( originalMetaFile );
							int removeMatteIndex = metaContents.IndexOf( removeMatteOption );
							if( removeMatteIndex >= 0 )
								removeMatte = metaContents[removeMatteIndex + removeMatteOption.Length] != '0';
						}

						SerializedProperty removeMatteProp = new SerializedObject( AssetImporter.GetAtPath( DUMMY_TEXTURE_PATH ) ).FindProperty( "m_PSDRemoveMatte" );
						if( removeMatteProp != null && removeMatteProp.boolValue != removeMatte )
						{
							removeMatteProp.boolValue = removeMatte;
							removeMatteProp.serializedObject.ApplyModifiedPropertiesWithoutUndo();
						}
					}

					// Temporarily copy the image file to Assets folder to create a read-write enabled Texture from it
					File.Copy( paths[i], DUMMY_TEXTURE_PATH, true );
					AssetDatabase.ImportAsset( DUMMY_TEXTURE_PATH, ImportAssetOptions.ForceUpdate );

					// Convert the Texture to PNG and save it
					byte[] pngBytes = AssetDatabase.LoadAssetAtPath<Texture2D>( DUMMY_TEXTURE_PATH ).EncodeToPNG();
					File.WriteAllBytes( pngFile, pngBytes );

					originalTotalSize += new FileInfo( paths[i] ).Length;
					convertedTotalSize += new FileInfo( pngFile ).Length;

					// Run OptiPNG to optimize the PNG
					if( optiPNGPath.Length > 0 && File.Exists( optiPNGPath ) )
					{
						try
						{
							Process.Start( new ProcessStartInfo( optiPNGPath )
							{
								Arguments = string.Concat( "-o ", optiPNGOptimization.ToString(), " \"", pngFile, "\"" ),
								CreateNoWindow = true,
								UseShellExecute = false
							} ).WaitForExit();
						}
						catch( Exception e )
						{
							Debug.LogException( e );
						}

						convertedTotalSizeOptiPNG += new FileInfo( pngFile ).Length;
					}

					// If .meta file exists, copy it to PNG image
					if( File.Exists( originalMetaFile ) )
					{
						File.Copy( originalMetaFile, pngMetaFile, true );

						// Try changing original meta file's GUID to avoid collisions with PNG (Credit: https://gist.github.com/ZimM-LostPolygon/7e2f8a3e5a1be183ac19)
						if( keepOriginalFiles )
						{
							string metaContents = File.ReadAllText( originalMetaFile );
							int guidIndex = metaContents.IndexOf( "guid: " );
							if( guidIndex >= 0 )
							{
								string guid = metaContents.Substring( guidIndex + 6, 32 );
								string newGuid = Guid.NewGuid().ToString( "N" );
								metaContents = metaContents.Replace( guid, newGuid );
								File.WriteAllText( originalMetaFile, metaContents );
							}
						}

						// Don't show "Remote Matte (PSD)" option for converted Textures
						if( isPSDImage )
						{
							string metaContents = File.ReadAllText( pngMetaFile );
							bool modifiedMeta = false;

							if( metaContents.Contains( "pSDShowRemoveMatteOption: 1" ) )
							{
								metaContents = metaContents.Replace( "pSDShowRemoveMatteOption: 1", "pSDShowRemoveMatteOption: 0" );
								modifiedMeta = true;
							}
							if( metaContents.Contains( "pSDRemoveMatte: 1" ) )
							{
								metaContents = metaContents.Replace( "pSDRemoveMatte: 1", "pSDRemoveMatte: 0" );
								modifiedMeta = true;
							}

							if( modifiedMeta )
								File.WriteAllText( pngMetaFile, metaContents );
						}
					}

					if( !keepOriginalFiles )
					{
						File.Delete( paths[i] );

						if( File.Exists( originalMetaFile ) )
							File.Delete( originalMetaFile );
					}

					convertedPaths.Add( paths[i] );
				}
			}
			catch( Exception e )
			{
				Debug.LogException( e );
			}
			finally
			{
				EditorUtility.ClearProgressBar();

				if( File.Exists( DUMMY_TEXTURE_PATH ) )
					AssetDatabase.DeleteAsset( DUMMY_TEXTURE_PATH );

				// Force Unity to import PNG images (otherwise we'd have to minimize Unity and then maximize it)
				AssetDatabase.Refresh();

				// Print information to Console
				StringBuilder sb = new StringBuilder( 100 + convertedPaths.Count * 75 );
				sb.Append( "Converted " ).Append( convertedPaths.Count ).Append( " Texture(s) to PNG in " ).Append( ( EditorApplication.timeSinceStartup - startTime ).ToString( "F2" ) ).Append( " seconds (" ).
					Append( EditorUtility.FormatBytes( originalTotalSize ) ).Append( " -> " ).Append( EditorUtility.FormatBytes( convertedTotalSize ) );

				if( convertedTotalSizeOptiPNG > 0L )
					sb.Append( " -> " ).Append( EditorUtility.FormatBytes( convertedTotalSizeOptiPNG ) ).Append( " with OptiPNG" );

				sb.AppendLine( "):" );
				for( int i = 0; i < convertedPaths.Count; i++ )
					sb.Append( "- " ).AppendLine( convertedPaths[i] );

				Debug.Log( sb.ToString() );
			}
		}

		GUILayout.EndScrollView();
	}

	private string PathField( GUIContent label, string path, bool isDirectory, string title, GUIContent downloadURL = null )
	{
		GUILayout.BeginHorizontal();
		path = EditorGUILayout.TextField( label, path );
		if( GUILayout.Button( "o", GL_WIDTH_25 ) )
		{
			string selectedPath = isDirectory ? EditorUtility.OpenFolderPanel( title, "", "" ) : EditorUtility.OpenFilePanel( title, "", "exe" );
			if( !string.IsNullOrEmpty( selectedPath ) )
				path = selectedPath;

			GUIUtility.keyboardControl = 0; // Remove focus from active text field
		}
		if( downloadURL != null && GUILayout.Button( downloadURL, GL_WIDTH_25 ) )
			Application.OpenURL( downloadURL.tooltip );
		GUILayout.EndHorizontal();

		return path;
	}

	private string[] FindTexturesToConvert()
	{
		HashSet<string> texturePaths = new HashSet<string>();
		HashSet<string> targetExtensions = new HashSet<string>( textureExtensions.Split( ';' ) );

		// Get directories to exclude
		string[] excludedPaths = excludedDirectories.Split( ';' );
		for( int i = 0; i < excludedPaths.Length; i++ )
		{
			excludedPaths[i] = excludedPaths[i].Trim();
			if( excludedPaths[i].Length == 0 )
				excludedPaths[i] = "NULL/";
			else
			{
				excludedPaths[i] = Path.GetFullPath( excludedPaths[i] );

				// Make sure excluded directory paths end with directory separator char
				if( Directory.Exists( excludedPaths[i] ) && !excludedPaths[i].EndsWith( Path.DirectorySeparatorChar.ToString() ) )
					excludedPaths[i] += Path.DirectorySeparatorChar;
			}
		}

		// Iterate through all files in Root Path
		string[] allFiles = Directory.GetFiles( rootPath, "*.*", SearchOption.AllDirectories );
		for( int i = 0; i < allFiles.Length; i++ )
		{
			// Only process filtered image files
			if( targetExtensions.Contains( Path.GetExtension( allFiles[i] ).ToLowerInvariant() ) )
			{
				bool isExcluded = false;
				if( excludedPaths.Length > 0 )
				{
					// Make sure the image file isn't part of an excluded directory
					string fileFullPath = Path.GetFullPath( allFiles[i] );
					for( int j = 0; j < excludedPaths.Length; j++ )
					{
						if( fileFullPath.StartsWith( excludedPaths[j] ) )
						{
							isExcluded = true;
							break;
						}
					}
				}

				if( !isExcluded )
					texturePaths.Add( allFiles[i] );
			}
		}

		string[] result = new string[texturePaths.Count];
		texturePaths.CopyTo( result );

		return result;
	}

	// Creates dummy Texture asset that will be used to read Textures' pixels
	private void CreateDummyTexture()
	{
		if( !File.Exists( DUMMY_TEXTURE_PATH ) )
		{
			File.WriteAllBytes( DUMMY_TEXTURE_PATH, new Texture2D( 2, 2 ).EncodeToPNG() );
			AssetDatabase.ImportAsset( DUMMY_TEXTURE_PATH, ImportAssetOptions.ForceUpdate );
		}

		TextureImporter textureImporter = AssetImporter.GetAtPath( DUMMY_TEXTURE_PATH ) as TextureImporter;
		textureImporter.maxTextureSize = maxTextureSize;
		textureImporter.isReadable = true;
		textureImporter.filterMode = FilterMode.Point;
		textureImporter.mipmapEnabled = false;
		textureImporter.alphaSource = TextureImporterAlphaSource.FromInput;
		textureImporter.npotScale = TextureImporterNPOTScale.None;
		textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
		textureImporter.SaveAndReimport();
	}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1130192.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C语言汇总

汇总一&#xff08;linux环境&#xff09; /bin &#xff1a;bin是二进制&#xff08;binary&#xff09;英文缩写。 /boot&#xff1a;存放的都是系统启动时要用到的程序。 /dev&#xff1a;包含了所有Linux系统中使用的外部设备。 /etc&#xff1a;存放了系统管理时要用到的…

uniapp中 background-image 设置背景图片不展示问题

有问题 <view class"file-picker__box jsz" tap"jszxszUpload(jsz)"></view>.jsz {background-image: url(../../static/example_drive.png); }解决1 <view class"file-picker__box jsz" :style"{ background-image: url(…

Android APP 隐藏系统软键盘的方法

1.场景描述&#xff1a; 1) APP项目中经常会开发自定义软键盘&#xff1b;同时在使用EditText时&#xff0c;也会常常遇到自动弹出系统自带的软键盘&#xff0c;与自定义的软键盘产生冲突的情况&#xff1b;此时需要禁止EditText自动弹出系统软键盘&#xff0c;从而使自定义的…

汽车电子专有名词与相应技术

1.EEA &#xff08;Electronic & Electrical Architecture 电子电气架构&#xff09; EEA在宏观上概括为物理架构与逻辑架构的结合&#xff0c;微观上通过众多电子元器件的协同配合&#xff0c;或集成式或分布式的系统级电子电气架构&#xff0c;具体详见专栏 新能源汽车电…

volatile 关键字有什么用?它的实现原理是什么?

volatile volatile是Java中的一个关键字&#xff0c;用于修饰变量&#xff0c;表示该变量是“易变的”&#xff08;Volatile&#xff09;。 volatile 关键字有两个作用&#xff1a; 可以保证在多线程环境下共享变量的可见性。 通过增加内存屏障防止多个指令之间的重排序。 可见…

【图结构从入门到应用】图的表示和遍历,图搜索算法详解与示例

1图的概念 图是一种非常常见的数据结构&#xff0c;用于表示对象之间的关系。在计算机科学中&#xff0c;有许多不同的图类型&#xff0c;包括有向图&#xff08;Directed Graph&#xff09;和无向图&#xff08;Undirected Graph&#xff09;。图通常由节点&#xff08;顶点&a…

vscode json文件添加注释报错

在vscode中创建json文件&#xff0c;想要注释一波时&#xff0c;发现报了个错&#xff1a;Comments are not permitted in JSON. (521)&#xff0c;意思是JSON中不允许注释 以下为解决方法&#xff1a; 在vscode的右下角中找到这个&#xff0c;点击 在出现的弹窗中输入json wit…

Python 自动化(十五)请求和响应

准备工作 将不同day下的代码分目录管理&#xff0c;方便后续复习查阅 (testenv) [rootlocalhost projects]# ls mysite1 (testenv) [rootlocalhost projects]# mkdir day01 day02 (testenv) [rootlocalhost projects]# cp -rf mysite1/ day01/ (testenv) [rootlocalhost proj…

vue路径中“@/“代表什么

举例&#xff1a; <img src"/../static/imgNew/adv/tupian.jpg"/>其中&#xff0c;/是webpack设置的路径别名&#xff0c;代表什么路径&#xff0c;要看webpack的build文件夹下webpack.base.conf.js里面对于是如何配置&#xff1a; 上图中代表src,上述代码就…

KDChart3.0编译过程-使用QT5.15及QT6.x编译

文章目录 参考原文一、下载KDChart源文件二、下载安装CMake三、编译Qt5.15.0 编译Qt6.x 编译使用Qt6.X编译的直接看这最快 四、使用测试方法一&#xff1a;测试方法二&#xff1a; 参考原文 记录我的KDChart3.0编译过程 系统&#xff1a;win11&#xff0c;Qt5.15 &#xff0c;编…

Android View拖拽/拖放DragAndDrop自定义View.DragShadowBuilder,Kotlin(2)

Android View拖拽/拖放DragAndDrop自定义View.DragShadowBuilder&#xff0c;Kotlin&#xff08;2&#xff09; import android.graphics.Canvas import android.graphics.Point import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.util…

关于前端如何下载后端接口返回content-type为application/octet-stream的文件

关于前端如何下载后端接口返回response-type为application/octet-stream的文件 问题描述 后端接口定义为直接返回一个文件&#xff0c;如果带认证信息可以直接通过浏览器url下载&#xff0c;但是接口需要传headers认证信息&#xff0c;url上又不支持传相关信息 解决 前端…

如何用 JMeter 编写性能测试脚本?

Apache JMeter 应该是应用最广泛的性能测试工具。怎么用 JMeter 编写性能测试脚本&#xff1f; 1. 编写 HTTP 性能测试脚本 STEP 1. 添加 HTTP 请求 img STEP 2. 了解配置信息 HTTP 请求各项信息说明&#xff08;以 JMeter 5.1 为例&#xff09;。 如下图所示&#xff1a;…

kibana监控

采取方式 Elastic Agent &#xff1a;更完善的功能 Metricbeat&#xff1a;轻量级指标收集&#xff08;采用&#xff09; 传统收集方法&#xff1a;使用内部导出器收集指标&#xff0c;已不建议 安装 metricbeat Download Metricbeat • Ship Metrics to Elasticsearch | E…

硬件安全与机器学习的结合

文章目录 1. A HT Detection and Diagnosis Method for Gate-level Netlists based on Machine Learning摘要Introduction 2. 基于多维结构特征的硬件木马检测技术摘要Instruction 3. A Hardware Trojan Detection and Diagnosis Method for Gate-Level Netlists Based on Diff…

第一章 系统工程概述|系统建模语言SysML实用指南学习

仅供个人学习记录 系统工程起因 期望当今系统能力较之前有显著提升。 竞争压力要求系统提升技术先进性&#xff1a;提高性能&#xff0c;同时降低成本及缩短交付周期 能力增长驱动需求增长&#xff0c;包括功能、互操作性、性能、可靠性提升与小型化等。 系统不再是孤立的&…

【软考系统架构设计师】2022年系统架构师综合知识真题及解析

本篇文章主要讲解2022年系统架构师综合知识真题及解析 【01】云计算服务体系结构如下图所示&#xff0c;图中①、②、③分别与SaaS、PaaS、Iaas相对应&#xff0c;图中①、②、③应为( )。 解析&#xff1a;答案选择B 从上到下&#xff0c;依次是应用层——平台层——基础设施…

【网络原理】| 应用层协议与传输层协议 (UDP)

&#x1f397;️ 主页&#xff1a;小夜时雨 &#x1f397;️ 专栏&#xff1a;javaEE初阶 &#x1f397;️ 乾坤未定&#xff0c;你我皆黑马 目录 一、应用层协议二、传输层协议&#xff08;UDP协议&#xff09; 一、应用层协议 应用层是和代码直接相关的一层&#xff0c;决定…

Spark集群中一个Worker启动失败的排错记录

文章目录 1 检查失败节点worker启动日志2 检查正常节点worker启动日志3 查看正常节点spark环境配置4 又出现新的ERROR4.1 报错解释4.2 报错解决思路4.3 端口报错解决操作 集群下电停机后再次启动时&#xff0c;发现其中一台节点的worker启动失败。 1 检查失败节点worker启动日…

常见排序算法之冒泡排序

冒泡排序&#xff0c;英文名Bubble Sort&#xff0c;是一种相对基础的 交换排序方法。这种排序算法的名字来源于它操作的过程&#xff0c;可以类比为数列中的每一个元素都可以像小气泡一样&#xff0c;根据自身的大小一点一点向数组的一侧移动。具体到冒泡排序的工作原理&#…