unity 如何将base64转为图片
时间: 2023-10-11 10:21:49 浏览: 103
要将Base64编码的字符串转换为图片,在Unity中可以使用以下代码:
```csharp
using System;
using UnityEngine;
using System.IO;
public static class ImageUtils
{
public static Texture2D Base64ToTexture2D(string base64)
{
byte[] imageBytes = Convert.FromBase64String(base64);
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(imageBytes);
return texture;
}
public static void SaveTextureToFile(Texture2D texture, string filePath)
{
byte[] bytes = texture.EncodeToPNG();
File.WriteAllBytes(filePath, bytes);
}
}
```
上面的代码中,`Base64ToTexture2D`方法将Base64编码的字符串转换为Texture2D对象,`SaveTextureToFile`方法将Texture2D对象保存为PNG文件。使用时,您可以将Base64字符串传递给`Base64ToTexture2D`方法,然后使用`SaveTextureToFile`方法将其保存为文件。
以下是使用示例:
```csharp
string base64 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABlBMVEUAAAD/" +
"////fwD///8p5hYAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZ" +
"cwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My4w" +
"OyBodHRwOi8vd3d3LnBhaW50Lm5ldC9zdmcvOFYzL2JpbmFyeS54bWwA/wAA" +
"AAD//z8L8AAAAJcEhZcwAADsIAAA7CARUoSoAAAAHdElNRQfiBRsJAxv3nYu" +
"AAABgklEQVQoz6WQPUvDUBDFf6XcXRy6R8JZGk2pW4jA6NqoXuA8F4j7NcXw" +
"SugdI2L9ApLq4KJ0i7Qd4q9e5/7gHcxd7Mn3nO+c3W3O5UtJ+LRf2hWTQlE" +
"ZatFxWInx6Yw8GZpkz1KsS2E1e4rVJG4cRgQxltbNvIu+2wFPhW8z0vWZkR" +
"vZVJL0QZ9L5A8aEc5xZg6zj2dXjB7L9mK3HW+0vZlB1m3EY1WzgJlRlj6cD" +
"9zjX5l9L+8hJZmK8eJ8wzESU8vL7+7Iy4tTz8HqQ4eNf7o5zCQ2vCvFvV3R" +
"e0b8HsJTAxIeesb4JYwhk0XHwAAAABJRU5ErkJggg==";
Texture2D texture = ImageUtils.Base64ToTexture2D(base64);
ImageUtils.SaveTextureToFile(texture, Application.dataPath + "/image.png");
```
上面的代码将Base64字符串转换为Texture2D对象,并将其保存为`image.png`文件。
阅读全文