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

本文主要是介绍[Unity]将所有 TGA、TIFF、PSD 和 BMP(可自定义)纹理转换为 PNG,以减小项目大小,而不会在 Unity 中造成任何质量损失,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

如何使用
只需在“项目”窗口中创建一个名为“编辑器”的文件夹,然后在其中添加此脚本即可。然后,打开窗口-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 folderif( 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 PNGif( 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' pixelsfor( 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)" optionif( 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 itFile.Copy( paths[i], DUMMY_TEXTURE_PATH, true );AssetDatabase.ImportAsset( DUMMY_TEXTURE_PATH, ImportAssetOptions.ForceUpdate );// Convert the Texture to PNG and save itbyte[] 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 PNGif( 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 imageif( 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 Texturesif( 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 ConsoleStringBuilder 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 excludestring[] 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 charif( Directory.Exists( excludedPaths[i] ) && !excludedPaths[i].EndsWith( Path.DirectorySeparatorChar.ToString() ) )excludedPaths[i] += Path.DirectorySeparatorChar;}}// Iterate through all files in Root Pathstring[] allFiles = Directory.GetFiles( rootPath, "*.*", SearchOption.AllDirectories );for( int i = 0; i < allFiles.Length; i++ ){// Only process filtered image filesif( 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 directorystring 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' pixelsprivate 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();}
}

这篇关于[Unity]将所有 TGA、TIFF、PSD 和 BMP(可自定义)纹理转换为 PNG,以减小项目大小,而不会在 Unity 中造成任何质量损失的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/282715

相关文章

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

Python实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

详解C++中类的大小决定因数

《详解C++中类的大小决定因数》类的大小受多个因素影响,主要包括成员变量、对齐方式、继承关系、虚函数表等,下面就来介绍一下,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 非静态数据成员示例:2. 数据对齐(Padding)示例:3. 虚函数(vtable 指针)示例:4. 继承普通继承虚继承5.

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

Java实现时间与字符串互相转换详解

《Java实现时间与字符串互相转换详解》这篇文章主要为大家详细介绍了Java中实现时间与字符串互相转换的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、日期格式化为字符串(一)使用预定义格式(二)自定义格式二、字符串解析为日期(一)解析ISO格式字符串(二)解析自定义

一文教你如何将maven项目转成web项目

《一文教你如何将maven项目转成web项目》在软件开发过程中,有时我们需要将一个普通的Maven项目转换为Web项目,以便能够部署到Web容器中运行,本文将详细介绍如何通过简单的步骤完成这一转换过程... 目录准备工作步骤一:修改​​pom.XML​​1.1 添加​​packaging​​标签1.2 添加

在java中如何将inputStream对象转换为File对象(不生成本地文件)

《在java中如何将inputStream对象转换为File对象(不生成本地文件)》:本文主要介绍在java中如何将inputStream对象转换为File对象(不生成本地文件),具有很好的参考价... 目录需求说明问题解决总结需求说明在后端中通过POI生成Excel文件流,将输出流(outputStre

tomcat多实例部署的项目实践

《tomcat多实例部署的项目实践》Tomcat多实例是指在一台设备上运行多个Tomcat服务,这些Tomcat相互独立,本文主要介绍了tomcat多实例部署的项目实践,具有一定的参考价值,感兴趣的可... 目录1.创建项目目录,测试文China编程件2js.创建实例的安装目录3.准备实例的配置文件4.编辑实例的