IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> Unity图片资源批量优化代码 -> 正文阅读

[游戏开发]Unity图片资源批量优化代码

?这里有两个方法。

一个是压缩图片到一个合适尺寸,比如将258*258的图片压缩成256成256的。

另一个是微小修改图片尺寸到一个合适值,让图片可以使用最优的压缩算法,比如将257*256的图片压缩成256成256的。

注意:代码执行需要一个System.Drawing.dll库文件,将库文件放到Resources目录下即可。文件可以到我的CSDN资源处下载。如有问题可留言沟通交流。

using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Drawing;


public class CompressTextureEditor
{
	const string TextureSize = "Assets/Com Tool/压缩Texture";
    [MenuItem(TextureSize, false, 1)]
    public static void CompressTextureSize()
    {
    	string[] assetGUIDArray = Selection.assetGUIDs;

        if (assetGUIDArray.Length == 1)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(assetGUIDArray[0]);
            Debug.Log(assetPath);
            List<string> filePaths = new List<string> ();
            string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
			string[] ImageType = imgtype.Split ('|');
			for (int i = 0; i < ImageType.Length; i++) {
				string[] dirs = Directory.GetFiles(assetPath, ImageType [i], SearchOption.AllDirectories);
				for (int j = 0; j < dirs.Length; j++) {
					filePaths.Add (dirs [j]);
				}
			}

			int[] size_r = {32, 64, 128, 256, 512, 1024, 2048};

			//"Assets/Game/"
			int index = 11;
			EditorUtility.DisplayProgressBar("TextureSize", "TextureSize...", 0);
			var count = 0;
			for (int i = 0; i < filePaths.Count; i++)
			{
				bool is_update = false;
				var filePath = filePaths [i];
				count++;
				EditorUtility.DisplayProgressBar("TextureSize", filePath, count / (float)filePaths.Count);

				TextureImporter textureImporter = AssetImporter.GetAtPath(filePath) as TextureImporter;

				string path = Path.GetDirectoryName (filePath);
				string spriteTag = path.Substring (index + 1, path.Length - index - 1);
				spriteTag = spriteTag.Replace ('/', '_');

				TextureImporterPlatformSettings platformSettings = textureImporter.GetPlatformTextureSettings("iPhone");
				
				if (platformSettings.overridden == true)
				{
					is_update = true;
					platformSettings.overridden = false;
					textureImporter.SetPlatformTextureSettings(platformSettings);
				}
	
				platformSettings = textureImporter.GetPlatformTextureSettings("Android");
				if (platformSettings.overridden == true)
				{
					is_update = true;
					platformSettings.overridden = false;
					textureImporter.SetPlatformTextureSettings(platformSettings);
				}

				Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D> (filePath);
				if (texture != null)
				{
					platformSettings = textureImporter.GetDefaultPlatformTextureSettings();

					int max_s = texture.width;
					int min_s = texture.height;
					if (max_s >= 32 || min_s >= 32)
					{
						if (max_s < texture.height)
						{
							min_s = texture.width;
							max_s = texture.height;
						}
						int max_jj = size_r.Length - 1;
						for (int j = 0; j < size_r.Length; j++)
						{
							if (j==0 && max_s <= size_r[j])
							{
								max_jj = j;
								break;
							}
							if (j!=size_r.Length && max_s <= size_r[j+1] && max_s > size_r[j])
							{
								max_jj = j;
								break;
							}
						}
						if ((max_jj+1)>=size_r.Length || (max_s < (size_r[max_jj] * 1.35)))
						{
							is_update = true;
							platformSettings.maxTextureSize = size_r[max_jj];
							textureImporter.SetPlatformTextureSettings(platformSettings);
						}
					}
					
				}
				if (is_update)
				{
					AssetDatabase.ImportAsset(filePath);
				}
			}

			EditorUtility.ClearProgressBar();
        }
    }


    // *****************************************************
    // *****************************************************
    // *****************************************************
	public class image_cls{
		public string new_path = "";
		public string old_path = "";
		public int max_size = 1024;
		public bool chg_size = false;
		public bool is_have = true;
    	public image_cls(string p1, string p2)
    	{
    		new_path = p1;
    		old_path = p2;
    	}
	}
	static List<image_cls> change_list = new List<image_cls>();
    static string temp_dir = Application.dataPath + "/temp_NewImg/";

    const string TextureExact4 = "Assets/Com Tool/修改图片尺寸(满足Unity%4)";
    [MenuItem(TextureExact4, false, 2)]
    public static void CompressTextureExact4()
    {
    	if (Directory.Exists (temp_dir)) {
			Directory.Delete (temp_dir, true);
		}
		Directory.CreateDirectory (temp_dir);

		change_list = new List<image_cls>();

    	string[] assetGUIDArray = Selection.assetGUIDs;

        if (assetGUIDArray.Length == 1)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(assetGUIDArray[0]);
            Debug.Log(assetPath);
            List<string> filePaths = new List<string> ();
            string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
			string[] ImageType = imgtype.Split ('|');
			for (int i = 0; i < ImageType.Length; i++) {
				string[] dirs = Directory.GetFiles(assetPath, ImageType [i], SearchOption.AllDirectories);
				for (int j = 0; j < dirs.Length; j++) {
					filePaths.Add (dirs [j]);
				}
			}

			int[] size_r = {32, 64, 128, 256, 512, 1024, 2048 ,4096};

			//"Assets/Game/"
			int index = 11;
			EditorUtility.DisplayProgressBar("1.YSTextureTag ", "YSTextureTag...", 0);
			var count = 0;
			for (int i = 0; i < filePaths.Count; i++) {
				bool is_update = false;
				var filePath = filePaths [i];
				count++;
				EditorUtility.DisplayProgressBar("1.YSTextureTag " + "(" + count + "/" + filePaths.Count + ")", filePath, count / (float)filePaths.Count);

				string path = Path.GetDirectoryName (filePath);
				string spriteTag = path.Substring (index + 1, path.Length - index - 1);
				spriteTag = spriteTag.Replace ('/', '_');

                // 第一种方式
	    //             var cIma = System.Drawing.Image.FromFile(filePath);
					// int width = cIma.Width;
	    //             int height = cIma.Height;
	    //             cIma.Dispose();

                // 第二种方式
				TextureImporter textureImporter = AssetImporter.GetAtPath(filePath) as TextureImporter;
                int width = 0;
                int height = 0;
                GetTextureOriginalSize(textureImporter, out width, out height);

                Debug.Log(width + ":" + height + "path = " + filePath);

				int max_s = width;
				int min_s = height;
                if (max_s >= 32 || min_s >= 32) {
					bool is_jh = false;
					if (max_s < height) {
						is_jh = true;
						min_s = width;
						max_s = height;
					}
					int max_jj = size_r.Length - 1;
					for (int j = 0; j < size_r.Length; j++) {
						if (j==0 && max_s <= size_r[j]) {
							max_jj = j;
							break;
						}
						if (j!=size_r.Length && max_s < size_r[j+1] && max_s >= size_r[j]) {
							max_jj = j;
							break;
						}
					}

            		var name = Path.GetFileNameWithoutExtension (filePath);
			        string copy_path = Path.GetDirectoryName (filePath);

			    	string new_path = temp_dir + name + ".png";
	                image_cls img_data = new image_cls(new_path, filePath);
			        change_list.Add(img_data);

					if ((max_jj+1)>=size_r.Length || (max_s < (size_r[max_jj] * 1.35))) {
				        img_data.max_size = size_r[max_jj];

						is_update = true;
						int mb_s = size_r[max_jj];
						float scale = (float)mb_s / max_s;
						int s1 = (int)Math.Round(scale * min_s, MidpointRounding.AwayFromZero);
						if (s1 % 4 != 0) {
							// 最小变化法
							if (s1 % 4 < 2) {
								s1 = s1 - s1 % 4;
							}
							else {
								s1 = s1 + 4 - s1 % 4;
							}
							min_s = (int)Math.Round(s1 / scale, MidpointRounding.AwayFromZero);
							img_data.chg_size = true;
							ChangeImage(new_path, filePath, min_s, max_s, is_jh, img_data);
						}
					}
					else {
						if (max_s % 4 != 0 && min_s % 4 == 0) {
							if (max_s % 4 < 2) {
								max_s = max_s - max_s % 4;
							}
							else {
								max_s = max_s + 4 - max_s % 4;
							}
							img_data.chg_size = true;
							ChangeImage(new_path, filePath, min_s, max_s, is_jh, img_data);
						}
						else if (max_s % 4 == 0 && min_s % 4 != 0) {
							if (min_s % 4 < 2) {
								min_s = min_s - min_s % 4;
							}
							else {
								min_s = min_s + 4 - min_s % 4;
							}
							img_data.chg_size = true;
							ChangeImage(new_path, filePath, min_s, max_s, is_jh, img_data);
						}
						else if (max_s % 4 != 0 && min_s % 4 != 0) {
							if (min_s % 4 < 2) {
								min_s = min_s - min_s % 4;
								max_s = max_s - max_s % 4;
							}
							else {
								min_s = min_s + 4 - min_s % 4;
								max_s = max_s + 4 - max_s % 4;
							}
							img_data.chg_size = true;
							ChangeImage(new_path, filePath, min_s, max_s, is_jh, img_data);
						}
					}
				}
			}
			EditorUtility.ClearProgressBar();

			EditorUtility.DisplayProgressBar("2.File Copy ", "2.File Copy ...", 0);
			count = 0;

			foreach (image_cls pp in change_list) {
				count++;
				EditorUtility.DisplayProgressBar("2.File Copy " + "(" + count + "/" + change_list.Count + ")", pp.old_path, count / (float)change_list.Count);
				if (pp.is_have && pp.chg_size) {
					System.IO.File.Copy(pp.new_path, pp.old_path, true);
					AssetDatabase.ImportAsset(pp.old_path);
				}
			}

			if (Directory.Exists (temp_dir)) {
				Directory.Delete (temp_dir, true);
			}

			AssetDatabase.Refresh();

			count = 0;
			EditorUtility.DisplayProgressBar("3.Set Image ", "3.Set Image ..."  , 0);
			foreach (image_cls pp in change_list) {
				count++;
				EditorUtility.DisplayProgressBar("3.Set Image " + "(" + count + "/" + change_list.Count + ")" , pp.old_path, count / (float)change_list.Count);
				if (pp.is_have && pp.max_size != null ) {
					TextureImporter textureImporter = AssetImporter.GetAtPath(pp.old_path) as TextureImporter;
					TextureImporterPlatformSettings platformSettings = textureImporter.GetDefaultPlatformTextureSettings();
					platformSettings.maxTextureSize = pp.max_size;
					textureImporter.SetPlatformTextureSettings(platformSettings);
					AssetDatabase.ImportAsset(pp.old_path);
				}
			}
			EditorUtility.ClearProgressBar();
        }
    }

    static public System.Drawing.Image GetFile(string path)
    {
        FileStream stream = File.OpenRead(path);
        int fileLength = 0;
        fileLength = (int)stream.Length;
        Byte[] image = new Byte[fileLength];
        stream.Read(image, 0, fileLength);
        System.Drawing.Image result = System.Drawing.Image.FromStream(stream);
        stream.Close();
        return result;
    }
    static public void ChangeImage(string new_path, string old_path, int min_s, int max_s, bool is_jh, image_cls img_cls)
    {
		System.Drawing.Image img = GetFile(old_path);
        Size s;
        if (is_jh) {
        	s = new Size(min_s, max_s);
        }
        else {
			s = new Size(max_s, min_s);
        }
		try
		{
 			Bitmap bit = new Bitmap(img, s);
        	SaveImage(bit, new_path, old_path);
			// var palette = bit.Palette;
		}
		catch
		{
			img_cls.is_have = false;
			Debug.LogError("old_path=" + old_path);
		}
    }
    static public void SaveImage(Bitmap bit, string new_path, string old_path)
    {
        bit.Save(new_path);
        bit.Dispose();
        //Debug.Log("大小调整:" + old_path);
        AssetDatabase.ImportAsset(new_path);
    }

    public static void GetTextureOriginalSize(TextureImporter ti, out int width, out int height)
    {
        if (ti == null)
        {
            width = 0;
            height = 0;
            return;
        }

        object[] args = new object[2] { 0, 0 };
        MethodInfo mi = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance);
        mi.Invoke(ti, args);

        width = (int)args[0];
        height = (int)args[1];
    }
}

?

  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2021-08-05 17:40:59  更:2021-08-05 17:41:30 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/6 7:51:38-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码