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.mzph.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;该脚本能够自动识别屏幕上的特定图像并执行点击操作。这种技术在自动化测试、批量操作和效率工具开发中有着广泛的应用前…