图片与字符串互转

[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(“}\n” );
}
File.AppendAllLines(Application.dataPath + “Image.txt”, fileContentsList);
Debug.Log(Application.dataPath + “Image.txt”);
}

//图片转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

Love

Title:图片与字符串互转

文章字数:169

Author:诸子百家-谁的天下?

Created At:2020-05-11, 11:41:32

Updated At:2021-10-02, 00:43:31

Url:http://yoursite.com/2020/05/11/Unity/Utils/%E5%B0%8F%E6%8A%80%E5%B7%A7/

Copyright: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

爱你,爱世人