Unity中如何将Base64字符串正确转换为有效PNG图片?
解决Unity C#中Stable Horde API Base64转有效PNG的问题
问题根源
Stable Horde API返回的img字段是Data URI格式(前缀为data:image/png;base64,),你的原始代码直接对完整字符串进行Base64解码,导致生成的文件包含无效数据,无法被识别为PNG。
正确实现代码
以下是对应Python逻辑的Unity C#版本,核心是先去除Data URI前缀,再处理字节流:
方法1:直接保存解码后的原始PNG字节(与Python逻辑一致,推荐)
using System.IO; using UnityEngine; public class StableHordeImageSaver : MonoBehaviour { public void SaveStableHordeImage(string base64Img, string filename, int? iter = null) { // 移除Data URI前缀 string pureBase64 = base64Img; const string prefix = "data:image/png;base64,"; if (pureBase64.StartsWith(prefix)) { pureBase64 = pureBase64.Substring(prefix.Length); } // 解码Base64为字节数组 byte[] imgBytes = Convert.FromBase64String(pureBase64); // 构造保存路径(示例用PersistentDataPath,可替换为你需要的路径) string savePath = Path.Combine(Application.persistentDataPath, filename); // 处理多图命名(对应Python中的多结果逻辑) if (iter.HasValue) { savePath = Path.Combine(Application.persistentDataPath, $"{iter.Value}_{filename}"); } // 写入文件 File.WriteAllBytes(savePath, imgBytes); } }
方法2:通过Unity Texture2D中转(确保格式兼容性)
如果直接保存字节仍有问题,可通过Texture2D加载并重新编码为标准PNG:
using System.IO; using UnityEngine; public class StableHordeImageSaver : MonoBehaviour { public void SaveStableHordeImage(string base64Img, string filename, int? iter = null) { // 移除Data URI前缀 string pureBase64 = base64Img; const string prefix = "data:image/png;base64,"; if (pureBase64.StartsWith(prefix)) { pureBase64 = pureBase64.Substring(prefix.Length); } byte[] imgBytes = Convert.FromBase64String(pureBase64); // 用Texture2D加载字节流 Texture2D texture = new Texture2D(2, 2); if (!texture.LoadImage(imgBytes)) // LoadImage自动识别图片格式 { Debug.LogError("Failed to load image data into Texture2D"); Destroy(texture); return; } // 编码为标准PNG字节 byte[] pngBytes = texture.EncodeToPNG(); // 构造保存路径 string savePath = Path.Combine(Application.persistentDataPath, filename); if (iter.HasValue) { savePath = Path.Combine(Application.persistentDataPath, $"{iter.Value}_{filename}"); } File.WriteAllBytes(savePath, pngBytes); Destroy(texture); // 销毁Texture释放内存 } }
使用说明
- 将
base64Img替换为你从myImageData.generations[0].img获取的字符串 - 多图场景下,传入
iter参数即可自动生成带索引的文件名 - 可替换
Application.persistentDataPath为你需要的保存路径(注意Unity不同平台的路径权限限制)
内容的提问来源于stack exchange,提问作者hitlab
相关产品推荐
相关产品推荐

