Texture转Texture2D
/// 运行模式下Texture转换成Texture2D
private Texture2D TextureToTexture2D(Texture texture)
{
Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
RenderTexture currentRT = RenderTexture.active;
RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
Graphics.Blit(texture, renderTexture);
RenderTexture.active = renderTexture;
texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture2D.Apply();
RenderTexture.active = currentRT;
RenderTexture.ReleaseTemporary(renderTexture);
return texture2D;
}
texture转byte数组
Convert.FromBase64String(textureStr)
字符串转color对象
方式一:unity内置方法
string colorStr = "#FFF7F4";
ColorUtility.TryParseHtmlString(colorStr, out Color color);
字节数组与字符串互转
Convert.ToBase64String(byte[] array)
byte[] bytes = Convert.FromBase64String(str)
System.Text.Encoding.UTF8.GetString(byte[]);
System.Text.Encoding.Default.GetString(byte[]);
图片文件转字串
/// <summary>
/// 将图片转化为字符串
/// </summary>
private string SetImageToString(string imgPath)
{
FileStream fs = new FileStream(imgPath, FileMode.Open);
byte[] imgByte = new byte[fs.Length];
fs.Read(imgByte, 0, imgByte.Length);
fs.Close();
return Convert.ToBase64String(imgByte);
}
字符串转换为纹理
private Texture2D GetTextureByString(string textureStr)
{
Texture2D tex = new Texture2D(1, 1);
byte[] arr = Convert.FromBase64String(textureStr);
tex.LoadImage(arr);
tex.Apply();
return tex;
}
将byte[]数组保存成文件
public static bool ByteToFile(byte[] byteArray, string fileName)
{
bool result = false;
try
{
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Write(byteArray, 0, byteArray.Length);
result = true;
}
}
catch
{
result = false;
}
return result;
}
将文件转换成byte[]数组
public static byte[] FileToByte(string fileUrl)
{
try
{
using (FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read))
{
byte[] byteArray = new byte[fs.Length];
fs.Read(byteArray, 0, byteArray.Length);
return byteArray;
}
}
catch
{
return null;
}
}
网友评论