Files
TaiWan/Assets/BatchTrimAndSaveImages.cs
2025-10-31 15:20:38 +08:00

51 lines
1.5 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
}
}
}