Unity Texture 下载、存储、使用

本文介绍在Unity中如何使用UnityWebRequest下载网络图片,并提供了详细的代码示例。此外,还介绍了如何将图片保存到本地,以及从本地加载图片进行使用的完整流程。

网络下载图片

// 2017之后推荐使用UnityWebRequest
IEnumerator DownloadTexture(string url){
    WWW www = new WWW (url);
    yield return www;
    if (www.isDone) {
        texture = www.texture;
    }
}

保存图片到本地

void SaveTexture(){
    string savePath = Application.persistentDataPath + "/test.png";
    // 文件流方式存储本读文件
    FileStream fs = new FileStream(savePath, FileMode.Open);
    byte[] buffer = new byte[fs.Length];
    fs.Read(buffer, 0, buffer.Length);
    fs.Close();
}

从本地加载图片并使用

void LoadTexture(){
    string savePath = Application.persistentDataPath + "/test.png";
    // 使用文件流读取本地图片文件
    FileStream fs = new FileStream(savePath, FileMode.Open);
    byte[] buffer = new byte[fs.Length];
    fs.Read(buffer, 0, buffer.Length);
    fs.Close();
    // 创建texture并设置图片格式,4通道32位,不使用mipmap
	texture = new Texture2D(1, 1, TextureFormat.ARGB4444, false);
    var iSLoad = texture.LoadImage(buffer);
    texture.Apply();
    // 创建精灵,中心点默认(0, 0)
    Sprite sprite = Sprite.Create (texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
}
由于Unity内置的Json处理工具JsonUtility对List与Dictionary支持欠佳,可选择使用LitJson作为对Json数据序列化与反序列化的处理工具,LitJson可从Github上下载获取,链接地址:LitJson [^1]。 要将Unity中的Texture图片存储为JSON文件,思路如下:首先将Texture数据换为可序列化的数据类型,例如字节数组,然后将其封装到合适的类中,最后使用LitJson将该类对象序列化为JSON字符串并保存为文件。以下是示例代码: ```csharp using System.IO; using UnityEngine; using LitJson; public class TextureToJson { public static void SaveTextureAsJson(Texture2D texture, string filePath) { // 将Texture2D换为字节数组 byte[] textureBytes = texture.EncodeToPNG(); // 将字节数组换为Base64字符串,以便可以在JSON中存储 string base64String = System.Convert.ToBase64String(textureBytes); // 创建一个包含图片数据的类 class TextureData { public string imageData; } TextureData data = new TextureData(); data.imageData = base64String; // 使用LitJson将数据序列化为JSON字符串 string json = JsonMapper.ToJson(data); // 将JSON字符串保存到文件 File.WriteAllText(filePath, json); } } ``` 使用时可以这样调用: ```csharp public class ExampleUsage : MonoBehaviour { public Texture2D targetTexture; public string savePath = "Assets/TextureData.json"; void Start() { if (targetTexture != null) { TextureToJson.SaveTextureAsJson(targetTexture, savePath); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值