Unity Texture 下载、存储、使用

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网络下载图片

// 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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值