using UnityEngine; using System.IO; using System.Collections.Generic; using System.Threading.Tasks; public class BatchTrimAndSaveImages : MonoBehaviour { public Texture2D[] textures; public string outputPath = "Assets/OutputImages"; private void Start() { CropTextures(); } void CropTextures() { if (textures == null || textures.Length == 0) return; foreach (var texture in textures) { var originalWidth = texture.width; var originalHeight = texture.height; // 确保宽度和高度是裁切后尺寸的整数倍 var width = Mathf.ClosestPowerOfTwo(originalWidth); var height = Mathf.ClosestPowerOfTwo(originalHeight); // 创建一个新的Texture2D,并裁剪原始纹理 var croppedTexture = new Texture2D(width, height); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var color = texture.GetPixel((int)(x * (originalWidth / (float)width)), (int)(y * (originalHeight / (float)height))); croppedTexture.SetPixel(x, y, color); } } // 应用所有设置的像素 croppedTexture.Apply(); // 保存裁剪后的纹理 var pngData = croppedTexture.EncodeToPNG(); File.WriteAllBytes(Path.Combine(outputPath, texture.name + ".png"), pngData); // 清理内存 DestroyImmediate(croppedTexture); } } }