unity 導入圖片后,可選擇精靈表自動切片,并可以導出為png

?腳本源代碼:

#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.IO;
using UnityEditorInternal;
using System.Collections.Generic;
using System;public class TextureImporterWindow : EditorWindow
{private string folderPath = "D:/";private string filePath = "D:/";private string searchPattern = "*.png";private string savePath = "C:/Users/26679/Desktop";[MenuItem("Tools/導入圖片")]public static void ShowWindow(){GetWindow<TextureImporterWindow>("導入圖片窗口");}[Obsolete]void OnGUI(){// 頂部留白10像素GUILayout.Space(10);EditorGUILayout.BeginVertical("box");GUILayout.Label("文件夾導入", EditorStyles.boldLabel);// 路徑設置folderPath = EditorGUILayout.TextField("文件夾路徑:", folderPath);// 文件過濾searchPattern = EditorGUILayout.TextField("篩選文件格式:", searchPattern);EditorGUILayout.BeginHorizontal();if (GUILayout.Button("瀏覽", GUILayout.Width(80))){folderPath = EditorUtility.OpenFolderPanel("選擇一個文件夾", "D:/", "");}// 導入按鈕if (GUILayout.Button("全部導入")){if (Directory.Exists(folderPath)){ImportTexturesFromFolder(folderPath, searchPattern);}else{EditorUtility.DisplayDialog("Error", "文件夾不存在!", "OK");}}EditorGUILayout.EndHorizontal();GUILayout.EndVertical();GUILayout.Space(20);EditorGUILayout.BeginVertical("box");GUILayout.Label("單個圖片導入", EditorStyles.boldLabel);EditorGUILayout.BeginHorizontal("box");filePath = EditorGUILayout.TextField("圖片路徑:", filePath);if (GUILayout.Button("瀏覽", GUILayout.Width(80))){// 打開文件選擇對話框filePath = EditorUtility.OpenFilePanel("請選擇圖片文件", "", "png,jpg,jpeg");}// 導入按鈕if (GUILayout.Button("導入")){if (!string.IsNullOrEmpty(filePath)){ImportTexturesFromFile(filePath);}else{EditorUtility.DisplayDialog("Error", "文件不存在!", "OK");}}EditorGUILayout.EndHorizontal();EditorGUILayout.EndVertical();GUILayout.Space(20);EditorGUILayout.BeginVertical("box");GUILayout.Label("將選中的Texture資源全部切片(用于將精靈表每一幀切割成片)", EditorStyles.boldLabel);// 切割按鈕if (GUILayout.Button("切片為Sprites")){// 獲取所有選中的紋理資源Texture2D[] textures = Selection.GetFiltered<Texture2D>(SelectionMode.Assets);if (textures.Length > 0){foreach (Texture2D texture in textures){string path = AssetDatabase.GetAssetPath(texture);TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter;if (importer != null){importer.textureType = TextureImporterType.Sprite;//紋理類型為Sprite// importer.spriteImportMode = SpriteImportMode.Single;//Sprite模式為多個;importer.filterMode = FilterMode.Point;//過濾模式為點; 對像素圖處理比較好,還有其它雙線算法;importer.textureCompression = TextureImporterCompression.Uncompressed;//不壓縮;importer.isReadable = true;//可讀寫;importer.maxTextureSize = 2048;importer.SaveAndReimport();}else{Debug.Log("導入設置失敗!");}DoAutomaticSlicing(false, texture);}}else{Debug.LogWarning("0 個Texture2D 資源被選中!");}}EditorGUILayout.BeginHorizontal("box");savePath = EditorGUILayout.TextField("保存路徑:", savePath);if (GUILayout.Button("瀏覽", GUILayout.Width(80))){// 打開文件選擇對話框savePath = EditorUtility.OpenFolderPanel("選擇一個文件夾", "D:/", "");}// 切割按鈕if (GUILayout.Button("切片導出png")){// 獲取所有選中的紋理資源Texture2D[] textures = Selection.GetFiltered<Texture2D>(SelectionMode.Assets);if (textures.Length > 0){foreach (Texture2D texture in textures){string path = AssetDatabase.GetAssetPath(texture);TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter;if (importer != null){importer.textureType = TextureImporterType.Sprite;//紋理類型為Spriteimporter.spriteImportMode = SpriteImportMode.Multiple;//Sprite模式為多個;importer.filterMode = FilterMode.Point;//過濾模式為點; 對像素圖處理比較好,還有其它雙線算法;importer.textureCompression = TextureImporterCompression.Uncompressed;//不壓縮;importer.isReadable = true;//可讀寫;importer.maxTextureSize = 2048;importer.SaveAndReimport();}else{Debug.Log("導入設置失敗!");}DoAutomaticSlicing(true, texture);}}else{Debug.LogWarning("0 個Texture2D 資源被選中!");}}EditorGUILayout.EndHorizontal();EditorGUILayout.EndVertical();GUILayout.Space(20);if (GUILayout.Button("test")){Debug.Log("This is a test!");//測試代碼;}}#region 圖片導入void ImportTexturesFromFolder(string path, string pattern){string[] files = Directory.GetFiles(path, pattern, SearchOption.AllDirectories);string projectPath = Application.dataPath;string targetFolder = "Assets/ImportedTextures/" + new DirectoryInfo(folderPath).Name + "/";// 創建目標文件夾if (!AssetDatabase.IsValidFolder(targetFolder)){AssetDatabase.CreateFolder("Assets", "ImportedTextures");AssetDatabase.CreateFolder("Assets/ImportedTextures", new DirectoryInfo(folderPath).Name);}int successCount = 0;foreach (string file in files){try{string fileName = Path.GetFileName(file);string destPath = Path.Combine(targetFolder, fileName);// 復制文件到項目目錄File.Copy(file, destPath, true);// Debug.Log($"復制: {file} -> {destPath}");successCount++;}catch (System.Exception e){Debug.LogError($"導入失敗 {file}: {e.Message}");}}// 刷新資源數據庫AssetDatabase.Refresh();// 設置導入設置foreach (string file in files){string fileName = Path.GetFileName(file);string assetPath = $"{targetFolder}{fileName}";TextureImporter importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;if (importer != null){importer.textureType = TextureImporterType.Sprite;//紋理類型為Spriteimporter.spriteImportMode = SpriteImportMode.Multiple;//Sprite模式為單個;importer.filterMode = FilterMode.Point;//過濾模式為點; 對像素圖處理比較好,還有其它雙線算法;importer.textureCompression = TextureImporterCompression.Uncompressed;//不壓縮;importer.isReadable = true;//可讀寫;importer.maxTextureSize = 2048;importer.SaveAndReimport();}else{Debug.Log("importer 為null");}}EditorUtility.DisplayDialog("導入完成",$"導入成功 {successCount}/{files.Length} textures", "OK");}void ImportTexturesFromFile(string file){string projectPath = Application.dataPath;string targetFolder = "Assets/ImportedTextures/";// 創建目標文件夾if (!AssetDatabase.IsValidFolder(targetFolder)){AssetDatabase.CreateFolder("Assets", "ImportedTextures");}try{string fileName = Path.GetFileName(file);string destPath = Path.Combine(targetFolder, fileName);// 復制文件到項目目錄File.Copy(file, destPath, true);// Debug.Log($"Copied: {file} -> {destPath}");// 刷新資源數據庫AssetDatabase.Refresh();// 設置導入設置string assetPath = $"Assets/ImportedTextures/{fileName}";TextureImporter importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;if (importer != null){importer.textureType = TextureImporterType.Sprite;//紋理類型為Spriteimporter.spriteImportMode = SpriteImportMode.Multiple;//Sprite模式為單個;importer.filterMode = FilterMode.Point;//過濾模式為點; 對像素圖處理比較好,還有其它雙線算法;importer.textureCompression = TextureImporterCompression.Uncompressed;//不壓縮;importer.isReadable = true;//可讀寫;importer.maxTextureSize = 2048;importer.SaveAndReimport();}EditorUtility.DisplayDialog("導入完成!",$"成功導入 1 textures", "OK");}catch (System.Exception e){Debug.LogError($"Failed to import {file}: {e.Message}");}}#endregion#region  Slice圖片[Obsolete]private void DoAutomaticSlicing(bool isExport, Texture2D OrigonTxr, int minimumSpriteSize = 4){Texture2D copyTexture = new Texture2D(OrigonTxr.width, OrigonTxr.height);copyTexture.SetPixels(OrigonTxr.GetPixels());copyTexture.Apply();Rect[] one = InternalSpriteUtility.GenerateAutomaticSpriteRectangles(copyTexture, minimumSpriteSize, 0);List<Rect> frames = new List<Rect>(one);frames = SortRects(frames, OrigonTxr.width);int index = 0;if (isExport){foreach (Rect frame in frames){ExportSpriteRectToPNG(OrigonTxr, frame, index++);}Debug.Log($"源{OrigonTxr.name}已經成功導出{index}張png圖片,并保存到:{savePath}");}else{string path = AssetDatabase.GetAssetPath(OrigonTxr);TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter;if (importer != null){importer.textureType = TextureImporterType.Sprite;//紋理類型為Spriteimporter.spriteImportMode = SpriteImportMode.Multiple;//Sprite模式為多個;importer.filterMode = FilterMode.Point;//過濾模式為點; 對像素圖處理比較好,還有其它雙線算法;importer.textureCompression = TextureImporterCompression.Uncompressed;//不壓縮;importer.isReadable = true;//可讀寫;importer.maxTextureSize = 2048;importer.SaveAndReimport();}else{Debug.Log("importer 為null");}List<SpriteMetaData> metas = new List<SpriteMetaData>();//于生成精靈的編輯器數據。表的名字;用于給子圖命名;foreach (Rect rect in frames)//生成精靈小圖;{SpriteMetaData meta = new SpriteMetaData();meta.rect = rect;meta.name = OrigonTxr.name + "_" + index++;metas.Add(meta);}importer.spritesheet = metas.ToArray();//精靈小圖數組添加到父精靈圖后;Debug.Log($"{OrigonTxr.name}成功生成{metas.Count} 個子Sprites ! ");}}// 1. Find top-most rectangle// 2. Sweep it vertically to find out all rects from that "row"// 3. goto 1.// This will give us nicely sorted left->right top->down list of rectangles// Works for most sprite sheets pretty nicelyprivate List<Rect> SortRects(List<Rect> rects, int width){List<Rect> result = new List<Rect>();while (rects.Count > 0){// Because the slicing algorithm works from bottom-up, the topmost rect is the last one in the arrayRect r = rects[rects.Count - 1];Rect sweepRect = new Rect(0, r.yMin, width, r.height);List<Rect> rowRects = RectSweep(rects, sweepRect);if (rowRects.Count > 0)result.AddRange(rowRects);else{// We didn't find any rects, just dump the remaining rects and continueresult.AddRange(rects);break;}}return result;}private List<Rect> RectSweep(List<Rect> rects, Rect sweepRect){if (rects == null || rects.Count == 0)return new List<Rect>();List<Rect> containedRects = new List<Rect>();foreach (Rect rect in rects){if (rect.Overlaps(sweepRect))containedRects.Add(rect);}// Remove found rects from original listforeach (Rect rect in containedRects)rects.Remove(rect);// Sort found rects by x positioncontainedRects.Sort((a, b) => a.x.CompareTo(b.x));return containedRects;}#endregion#region  導出 png文件// public Sprite spriteToExport;// public Rect rectToExport;private void ExportSpriteRectToPNG(Texture2D texture, Rect rectToExport, int index){if (texture == null){Debug.LogError("要導出的源Texture2D為空!");return;}// 計算裁剪區域在Texture2D中的實際坐標int x = (int)rectToExport.x;int y = (int)rectToExport.y;int width = (int)rectToExport.width;int height = (int)rectToExport.height;// 創建新的Texture2D對象,用于存儲裁剪后的像素數據Texture2D outputTexture = new Texture2D(width, height, TextureFormat.RGBA32, false);Color[] pixels = texture.GetPixels(x, y, width, height);outputTexture.SetPixels(pixels);outputTexture.Apply();// 編碼為PNG格式byte[] pngData = outputTexture.EncodeToPNG();// 保存文件if (pngData != null){// string filenameNoExtension = Path.GetFileNameWithoutExtension('origonPath');File.WriteAllBytes(savePath + "/" + texture.name + '_' + index + ".png", pngData);}else{Debug.LogError("無法將" + savePath + texture.name + '_' + index + ".png" + "編碼為PNG文件!");}}#endregion}
#endif

演示:?

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/80057.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/80057.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/80057.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

使用 Azure DevSecOps 和 AIOps 構建可擴展且安全的多區域金融科技 SaaS 平臺

引言 金融科技行業有一個顯著特點&#xff1a;客戶期望能夠隨時隨地即時訪問其財務數據&#xff0c;并且對宕機零容忍。即使是短暫的中斷也會損害用戶的信心和忠誠度。與此同時&#xff0c;對數據泄露的擔憂已將安全提升到整個行業的首要地位。 在本文中&#xff0c;我們將探…

基于Django框架開發的B2C天天生鮮電商平臺

天天生鮮 介紹 天天生鮮是一個基于Django框架開發的B2C(Business-to-Customer)電商平臺&#xff0c;專注于生鮮食品的在線銷售。該項目采用了主流的Python Web開發框架Django&#xff0c;結合MySQL數據庫、Redis緩存等技術&#xff0c;實現了一個功能完整、界面友好的電商網站…

ASP.NET MVC4 技術單選及多選題目匯編

一、單選題&#xff08;共50題&#xff0c;每題2分&#xff09; 1、ASP.NET MVC4 的核心架構模式是什么&#xff1f; A. MVP B. MVVM C. MVC D.三層架構 答案&#xff1a;C 2、在 MVC4 中&#xff0c;默認的路由配置文件名是&#xff1f; A. Global.asax B. RouteConfig.cs C.…

26屆秋招收割offer指南

26屆暑期實習已經陸續啟動&#xff0c;這也意味著對于26屆的同學們來說&#xff0c;“找工作”已經提上了日程。為了幫助大家更好地準備暑期實習和秋招&#xff0c;本期主要從時間線、學習路線、核心知識點及投遞幾方面給大家介紹&#xff0c;希望能為大家提供一些實用的建議和…

數據中心機電建設

電氣系統 供配電系統 設計要求&#xff1a;數據中心通常需要雙路市電供電&#xff0c;以提高供電的可靠性。同時&#xff0c;配備柴油發電機組作為備用電源&#xff0c;確保在市電停電時能及時為關鍵設備供電。根據數據中心的規模和設備功耗&#xff0c;精確計算電力負荷&…

每日一題洛谷P1025 [NOIP 2001 提高組] 數的劃分c++

P1025 [NOIP 2001 提高組] 數的劃分 - 洛谷 (luogu.com.cn) #include<iostream> using namespace std; int n, k; int res 0; void dfs(int num,int step,int sum) {//判斷if (sum n) {if (step k) {res;return;}}if (sum > n || step k)return;//搜索for (int i …

大模型推理--從零搭建大模型推理服務器:硬件選購、Ubuntu雙系統安裝與環境配置

自從大模型火了之后就一直想自己組裝一臺機器去深入研究一下大模型&#xff0c;奈何囊中羞澀&#xff0c;遲遲也沒有行動。在下了很大的勇氣之后&#xff0c;終于花了接近4萬塊錢組裝了一臺臺式機&#xff0c;下面給大家詳細介紹一下我的裝機過程。 1.硬件配置 研究了一周&am…

第35周Zookkeeper+Dubbo Dubbo

Dubbo 詳解 一、Dubbo 是什么 官網與定義 Dubbo 是一款高性能、輕量級的開源服務框架&#xff0c;其官網為 double.apache.org&#xff0c;提供中文版本&#xff08;網址含 “zh”&#xff09;。 核心能力 Dubbo 具備六大核心能力&#xff1a; 面向接口代理的高性能 RPC …

NX二次開發——BlockUI 彈出另一個BlockUI對話框

最近在研究&#xff0c;裝配體下自動導出BOM表格中需要用到BlockUI 彈出另一個BlockUI對話框。通過對網上資料進行整理總結&#xff0c;具體如下&#xff1a; 1、明確主對話框、子對話框1和子對話框2 使用BlockUI創建.cpp和.hpp文件&#xff0c;dlx文件內容如下所示 主對話框…

PostgreSQL 系統管理函數詳解

PostgreSQL 系統管理函數詳解 PostgreSQL 提供了一系列強大的系統管理函數&#xff0c;用于數據庫維護、監控和配置。這些函數可分為多個類別&#xff0c;以下是主要功能的詳細說明&#xff1a; 一、數據庫配置函數 1. 參數管理函數 -- 查看所有配置參數 SELECT name, sett…

【2025軟考高級架構師】——計算機網絡(9)

摘要 全文主要圍繞計算機網絡相關知識展開&#xff0c;包括域名服務器查詢方式、網絡規劃與設計的關鍵技術、雙協議棧與隧道技術、層次化網絡設計、網絡冗余設計以及高可靠和高可用性等方面&#xff0c;旨在為軟考高級架構師的備考提供知識參考。 1. 通信網絡架構圖 2. 通信架…

yolov8n-obb訓練rknn模型

必備&#xff1a; 準備一臺ubuntu22的服務器或者虛擬機&#xff08;x86_64&#xff09; 1、數據集標注&#xff1a; 1&#xff09;推薦使用X-AnyLabeling標注工具 2&#xff09;標注選【旋轉框】 3&#xff09;可選AI標注&#xff0c;再手動補充&#xff0c;提高標注速度 …

前端-HTML+CSS+JavaScript+Vue+Ajax概述

HTML&#xff08;超文本標記語言&#xff09;常見標簽 <html><head> <title>這是標題的內容&#xff0c;顯示在瀏覽器的頭部</title></head><body><!-- 這里面的內容在瀏覽器顯示給用戶看 --><!-- h1 -> h6 : 標題從大到小 …

嵌入式軟件--stm32 DAY 5 USART串口通訊(上)

前邊我們學的都是通用的功能&#xff0c;例如GPIO、中斷&#xff0c;現在我們要學習的是某一個特定的功能。典型的就是通訊功能。其中&#xff0c;最簡單的通訊協議就是串口了。 一、串口_通訊基礎知識 1.1 串行與并行 按數據傳送的方式分類的。 串行通信一位一位傳輸&…

c++混淆工具Hikari-LLVM15-llvm-18.1.8rel編譯安裝

目錄 1. windows 編譯1. 2 編譯工具安裝1.2.1 下載w64devkit1.2.2 添加環境變量1.2.3 驗證一下 1.3 下載llvm-18.1.8rel1.4 編譯 2. Android studio增加混淆編譯2.1 替換NDK中clang2.2 配置混淆編譯項 3. Linux編譯安裝4. Linux下增加混淆編譯4.1 在CMakeLists.txt中設置clang編…

【EasyPan】loadDataList方法及checkRootFilePid方法解析

【EasyPan】項目常見問題解答&#xff08;自用&持續更新中…&#xff09;匯總版 一、loadDataList方法概覽 /*** 文件列表加載接口* param session HTTP會話對象* param shareId 必須參數&#xff0c;分享ID&#xff08;使用VerifyParam進行非空校驗&#xff09;* param …

Vue3渲染引擎:虛擬DOM與響應式原理

Vue3渲染引擎&#xff1a;虛擬DOM與響應式原理 在當今的前端開發中&#xff0c;Vue.js作為一種流行的JavaScript框架&#xff0c;經常被用來構建用戶界面。而Vue.js 3作為其最新版本&#xff0c;在性能和功能上進行了許多優化和改進。其中&#xff0c;Vue3渲染引擎的核心原理—…

【論文閱讀】Attentive Collaborative Filtering:

Attentive Collaborative Filtering: Multimedia Recommendation with Item- and Component-Level Attention Attentive Collaborative Filtering (ACF)、隱式反饋推薦、注意力機制、貝葉斯個性化排序 標題翻譯&#xff1a;注意力協同過濾&#xff1a;基于項目和組件級注意力的…

【PostgreSQL數據分析實戰:從數據清洗到可視化全流程】2.1 數據查詢基礎(SELECT/WHERE/GROUP BY/HAVING)

?? 點擊關注不迷路 ?? 點擊關注不迷路 ?? 點擊關注不迷路 文章大綱 第2章 SQL語法進階:數據查詢基礎(SELECT/WHERE/GROUP BY/HAVING)2.1 數據查詢基礎2.1.1 SELECT 語句:從表中提取數據2.1.1.1 基礎語法與列選擇2.1.1.2 列別名與表達式2.1.1.3 去重與排序2.1.2 WHERE…

深度解析:基于Python的微信小程序自動化操作實現

引言 在當今數字化時代&#xff0c;自動化技術正在改變我們與軟件交互的方式。本文將深入解析一個使用Python實現的微信小程序自動化操作腳本&#xff0c;該腳本能夠自動識別屏幕上的特定圖像并執行點擊操作。這種技術在自動化測試、批量操作和效率工具開發中有著廣泛的應用前…