🖼️ Unity 图片与 Base64 互转:资源嵌入与编码转换实战

💡 为什么需要图片与字符串互转?

  • 如何将图片嵌入代码,避免资源加载问题?
  • 如何通过网络传输图片数据?
  • Base64 编码在 Unity 中如何使用?
  • 如何批量处理图片资源?

实战教程!掌握图片与 Base64 字符串互转技术,灵活处理图片资源!

[MenuItem(“test/test”)]
public static void ShowImage()
{
string headerPath = Application.dataPath + “/zhuzizheng/Images/“;
List fileContentsList = new List();
var files = Directory.GetFiles(headerPath, “*.png”);
foreach (var fileName in files)
{
Debug.Log(fileName);
fileContentsList.Add(string.Format(“public static Texture2D {0}Image()”, fileName.Replace(headerPath,””).Replace(“.png”,””)));
fileContentsList.Add(“{“);
fileContentsList.Add(“ string base64PNG =”);
fileContentsList.Add(“ ““ + Texture2dToBase64(fileName) + “”;” );
fileContentsList.Add(“ return LoadBase64String(base64PNG);” );
fileContentsList.Add(“}
” );
}
File.AppendAllLines(Application.dataPath + “Image.txt”, fileContentsList);
Debug.Log(Application.dataPath + “Image.txt”);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//图片转base64string
public static string Texture2dToBase64(string texture2d_path)
{
//将图片文件转为流文件
FileStream fs = new System.IO.FileStream(texture2d_path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] thebytes = new byte[fs.Length];

fs.Read(thebytes, 0, (int)fs.Length);
//转为base64string
string base64_texture2d = Convert.ToBase64String(thebytes);
return base64_texture2d;
}
//字符串转图片
private static Texture2D LoadBase64String(string base64PNG)
{
Texture2D pic = new Texture2D(1024, 1024);
byte[] data = System.Convert.FromBase64String(base64PNG);
pic.LoadImage(data);
byte[] bytes = pic.EncodeToPNG();
return pic;
}
    转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1487842110@qq.com