摘要:Unity圖片空白像素批量處理工具
該工具提供兩種方式批量剔除圖片空白像素:
靜態處理類:提供TrimTexture方法,可讀取紋理像素數據,計算非透明區域邊界,生成裁剪后的新紋理;SaveTexture方法保存處理結果。
編輯器窗口:通過"Tools/UI"菜單打開窗口,支持多選PNG圖片后批量處理。主要流程包括:加載選中項→分析像素邊界→裁剪保存→恢復原始設置。處理時臨時修改紋理為可讀狀態,完成后自動刷新資源庫并統計成功數量。適用于UI圖片資源優化,需在Unity編輯器環境下使用。
using UnityEditor;
using UnityEngine;
using System.IO;public static class ImageTrimmerHandle
{public static Texture2D TrimTexture(Texture2D sourceTexture){if (sourceTexture == null) return null;string assetPath = AssetDatabase.GetAssetPath(sourceTexture);TextureImporter importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;if (importer == null) return null;bool originalReadable = importer.isReadable;TextureImporterCompression originalCompression = importer.textureCompression;// 設置為可讀importer.isReadable = true;importer.textureCompression = TextureImporterCompression.Uncompressed;AssetDatabase.ImportAsset(assetPath);AssetDatabase.Refresh();// 重新加載紋理Texture2D readableTexture = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);Color[] pixels = readableTexture.GetPixels();// 找到邊界int width = readableTexture.width;int height = readableTexture.height;int left = width;int right = 0;int top = 0;int bottom = height;for (int y = 0; y < height; y++){for (int x = 0; x < width; x++){Color pixel = pixels[y * width + x];if (pixel.a > 0.01f) // 非完全透明{left = Mathf.Min(left, x);right = Mathf.Max(right, x);top = Mathf.Max(top, y);bottom = Mathf.Min(bottom, y);}}}// 創建新紋理int newWidth = right - left + 1;int newHeight = top - bottom + 1;Texture2D trimmedTexture = null;if (newWidth > 0 && newHeight > 0){trimmedTexture = new Texture2D(newWidth, newHeight, TextureFormat.RGBA32, false);Color[] newPixels = new Color[newWidth * newHeight];for (int y = bottom; y <= top; y++){for (int x = left; x <= right; x++){int sourceIndex = y * width + x;int destIndex = (y - bottom) * newWidth + (x - left);newPixels[destIndex] = pixels[sourceIndex];}}trimmedTexture.SetPixels(newPixels);trimmedTexture.Apply();}// 恢復原始導入設置importer.isReadable = originalReadable;importer.textureCompression = originalCompression;AssetDatabase.ImportAsset(assetPath);return trimmedTexture;}public static void SaveTexture(Texture2D texture, string savePath){if (texture == null || string.IsNullOrEmpty(savePath)) return;byte[] bytes = texture.EncodeToPNG();string directory = Path.GetDirectoryName(savePath);if (!Directory.Exists(directory)){Directory.CreateDirectory(directory);}File.WriteAllBytes(savePath, bytes);AssetDatabase.Refresh();Debug.Log("圖片已保存至: " + savePath);// 自動選擇保存的資源Texture2D savedTexture = AssetDatabase.LoadAssetAtPath<Texture2D>(savePath);if (savedTexture != null){Selection.activeObject = savedTexture;}}
}
using UnityEditor;
using UnityEngine;
using System.IO;public class ImageTrimmerWindow : EditorWindow
{private Object[] selectedTextures;[MenuItem("Tools/UI/批量剔除圖片的空白像素")]public static void ShowWindow(){GetWindow<ImageTrimmerWindow>("批量剔除圖片的空白像素");}private void OnGUI(){GUILayout.Label("批量圖片空白像素剔除", EditorStyles.boldLabel);EditorGUILayout.Space();EditorGUILayout.HelpBox("請選擇一個或多個 PNG 圖片文件(可在Project窗口多選后點擊“從選中項加載”)。", MessageType.Info);if (GUILayout.Button("從選中項加載")){selectedTextures = Selection.GetFiltered(typeof(Texture2D), SelectionMode.Assets);}if (selectedTextures != null && selectedTextures.Length > 0){EditorGUILayout.LabelField($"已選擇圖片數量: {selectedTextures.Length}");if (GUILayout.Button("批量剔除并覆蓋保存")){int successCount = 0;foreach (Object obj in selectedTextures){Texture2D tex = obj as Texture2D;if (tex == null) continue;Texture2D trimmed = ImageTrimmerHandle.TrimTexture(tex);if (trimmed != null){string path = AssetDatabase.GetAssetPath(tex);ImageTrimmerHandle.SaveTexture(trimmed, path);successCount++;}}AssetDatabase.Refresh();EditorUtility.DisplayDialog("處理完成", $"已處理并覆蓋保存 {successCount} 張圖片。", "確定");}}else{EditorGUILayout.LabelField("未選擇圖片。");}}
}