84 lines
2.5 KiB
C#
84 lines
2.5 KiB
C#
using UnityEngine;
|
||
using UnityEngine.UI;
|
||
using System.IO;
|
||
|
||
public class ImageBlender : MonoBehaviour
|
||
{
|
||
[Header("绑定设置")]
|
||
public Image imageA; // 底图
|
||
public Image imageB; // 顶图
|
||
public Shader blendShader;
|
||
|
||
[Header("导出设置")]
|
||
public string fileName = "Blended_Result";
|
||
public string saveFolder = "Exports";
|
||
|
||
void Start()
|
||
{
|
||
// 自动获取Shader(可选)
|
||
if (!blendShader) blendShader = Shader.Find("Custom/SimpleBlend");
|
||
}
|
||
|
||
[ContextMenu("执行混合导出")]
|
||
public void ExecuteBlendExport()
|
||
{
|
||
// 获取原始纹理
|
||
Texture2D texA = GetImageTexture(imageA);
|
||
Texture2D texB = GetImageTexture(imageB);
|
||
|
||
// 创建临时RenderTexture
|
||
RenderTexture rt = new RenderTexture(texA.width, texA.height, 24);
|
||
|
||
// 创建混合材质
|
||
Material blendMat = new Material(blendShader);
|
||
blendMat.SetTexture("_MainTex", texA);
|
||
blendMat.SetTexture("_BlendTex", texB);
|
||
|
||
// 执行混合
|
||
Graphics.Blit(null, rt, blendMat);
|
||
|
||
// 转换为Texture2D
|
||
Texture2D output = RenderTextureToTexture2D(rt);
|
||
|
||
// 保存文件
|
||
SaveTextureAsPNG(output);
|
||
|
||
// 清理资源
|
||
DestroyImmediate(rt);
|
||
DestroyImmediate(output);
|
||
}
|
||
|
||
Texture2D GetImageTexture(Image image)
|
||
{
|
||
// 从Image组件获取纹理
|
||
Sprite sprite = image.sprite;
|
||
Texture2D originTex = sprite.texture;
|
||
|
||
// 创建可读写副本
|
||
Texture2D copyTex = new Texture2D(originTex.width, originTex.height, originTex.format, false);
|
||
copyTex.SetPixels(originTex.GetPixels());
|
||
copyTex.Apply();
|
||
return copyTex;
|
||
}
|
||
|
||
Texture2D RenderTextureToTexture2D(RenderTexture rt)
|
||
{
|
||
RenderTexture.active = rt;
|
||
Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
|
||
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
|
||
tex.Apply();
|
||
RenderTexture.active = null;
|
||
return tex;
|
||
}
|
||
|
||
void SaveTextureAsPNG(Texture2D tex)
|
||
{
|
||
byte[] bytes = tex.EncodeToPNG();
|
||
string dirPath = Path.Combine(Application.streamingAssetsPath, saveFolder);
|
||
if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
|
||
|
||
string filePath = Path.Combine(dirPath, fileName + ".png");
|
||
File.WriteAllBytes(filePath, bytes);
|
||
Debug.Log($"导出成功:{filePath}");
|
||
}
|
||
} |