Unity3D(C#)中如何将Texture2D图像数据转Base64并存为JSON文件
Unity 2020.3 Texture2D转Base64并存储为JSON实现方案
你当前的代码存在以下可优化/错误点:
- 重复调用
texture.EncodeToPNG()执行了两次编码,造成不必要的性能损耗- 最终写入文件时直接传入了原始Base64字符串,而非
JsonUtility序列化后的结果,导致生成的文件不是标准JSON格式- 未考虑实时渲染得到的Texture2D不可读的异常场景,也未处理存储路径的权限问题
前置要求
- 用于截图的Texture2D需要开启可读属性:从RenderTexture实时转换的纹理不需要额外配置,手动导入的静态纹理需要在导入面板勾选「Read/Write Enabled」
- 提前引入必要命名空间:
using System; using System.IO; using UnityEngine;
完整实现代码
以下代码包含从相机实时截图、转Base64到存储为JSON的全流程:
/// <summary> /// 实时获取相机截图转Base64并存为JSON文件 /// </summary> /// <param name="targetCamera">要截图的目标相机</param> /// <param name="saveFileName">保存的JSON文件名(无需后缀)</param> public void SaveCameraScreenshotToJson(Camera targetCamera, string saveFileName = "ScreenshotData") { // 1. 获取目标相机的实时渲染纹理 RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 24); targetCamera.targetTexture = rt; targetCamera.Render(); // 2. 将RenderTexture转为可读的Texture2D Texture2D screenshotTex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); RenderTexture.active = rt; screenshotTex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); screenshotTex.Apply(); // 清理临时渲染资源,避免内存泄漏 targetCamera.targetTexture = null; RenderTexture.active = null; Destroy(rt); // 3. 单次编码为PNG后转Base64字符串 byte[] pngBytes = screenshotTex.EncodeToPNG(); string base64Str = Convert.ToBase64String(pngBytes); // 4. 序列化为标准JSON格式,可自定义扩展字段 string jsonResult = JsonUtility.ToJson(new ScreenshotData { base64Content = base64Str }); // 5. 写入文件,使用persistentDataPath避免打包后读写权限异常 string savePath = Path.Combine(Application.persistentDataPath, $"{saveFileName}.json"); File.WriteAllText(savePath, jsonResult); // 可选调用网页端screenshot方法 // Application.ExternalCall("screenshot", base64Str); Debug.Log($"JSON文件已保存到:{savePath}"); } /// <summary> /// 序列化用数据包装类,可按需扩展字段 /// </summary> [Serializable] public class ScreenshotData { public string base64Content; // 可扩展其他字段,比如截图分辨率、时间戳等 // public int width; // public int height; // public string timestamp; }
注意事项
- 不要直接用
Application.dataPath作为存储路径,该路径在打包后为只读路径,会触发写入失败 - 若需要自定义截图分辨率,修改
RenderTexture和Texture2D的宽高参数即可,无需和屏幕分辨率一致
内容的提问来源于stack exchange,提问作者Ali Hussain
相关产品推荐
相关产品推荐

