【Unity3D】读取Android SDcard文件

本文介绍了在Unity中通过两种不同方法加载SDCard上的图片资源的过程。一是使用IO方式加载,涉及文件流操作及纹理创建;二是利用WWW方式加载本地图片资源。

一、添加权限

权限添加 :Player settings -- Other settings -- write permission的设置 Sdcard。这个是在Unity编辑器里打包的情况。

如果导出到studio 里面的话,可自行修改Manifest文件。

 

二、两种方式

IO方式 加载sdcard上的图片资源

加载的  /storage/emulated/0/ProjectName/image.jpg,

image = this.GetComponentInChildren<Image>(); 
   
      Debug.Log("IO加载用时: image = this.GetComponent<Image> ==========  " + image); 
   
      Debug.Log("IO加载:  Application.dataPath "  + Application.dataPath ); 
      // Application.dataPath /data/app/com.putao.ptx.core-1/base.apk 
   
      Debug.Log("IO加载:  Application.persistentDataPath " + Application.persistentDataPath); 
      // Application.persistentDataPath /storage/emulated/0/Android/data/com.putao.ptx.core/files  
   
   
      Debug.Log("IO加载:GameObject.Find" + GameObject.Find("Canvas/Avator").GetComponent<Image>()); 
   
       // /data/user/0/com.putao.paichallenge/cache/20170524_130527.jpg 
   
   
      // path =======  "/storage/emulated/0/ProjectName/image.jpg" 
      FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); 
      fileStream.Seek(0, SeekOrigin.Begin); 
      //创建文件长度缓冲区 
      byte[] bytes = new byte[fileStream.Length]; 
      //读取文件 
      fileStream.Read(bytes, 0, (int)fileStream.Length); 
      //释放文件读取流 
      fileStream.Close(); 
      fileStream.Dispose(); 
      fileStream = null; 
   
      //创建Texture 
      int width = 300; 
      int height = 372; 
      Texture2D texture = new Texture2D(width, height); 
      texture.LoadImage(bytes); 
   
   
      //创建Sprite      
      Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width,texture.height), new Vector2(0.5f, 0.5f)); 
   
      image.sprite = sprite; 

 

log上可以看出来  android上 getExternalFilesDir("") 和 Unity里面的Application.persistentDataPath是一致的

   /storage/emulated/0/Android/data/com.putao.ptx.core/files

WWW方式加载本地图片   

url=  "file://"+ "/storage/emulated/0/ProjectName/image.jpg"

根本不是加"jar:file://..."

public void LoadByWWW(String path) 
    { 
        StartCoroutine(doLoadByWWW(path)); 
   
    } 
   
    IEnumerator doLoadByWWW(String path) 
    { 
        string url = "file://" + "/storage/emulated/0/PaiChallenge/image.jpg"; 
        Debug.Log("doLoadByWWW == url ==================   " + url); 
   
        WWW w = new WWW(url); 
   
        yield return w; 
   
        if (w.isDone) 
        { 
            Sprite sprite = Sprite.Create(w.texture, new Rect(0, 0, w.texture.width, w.texture.height), new Vector2(0.5f, 0.5f)); 
   
            GameObject.Find("Canvas/Avator").GetComponent<Image>().sprite = sprite; 
   
        } 

### 访问并读取 Android 设备 SDCard 文件的方法 #### 方法概述 为了使 Unity 应用程序能够访问并读取 Android 设备上的 SDCard 文件,需确保应用程序具有必要的权限,并采用适当的方式定位目标文件路径。 #### 权限设置 对于较新的 Android 版本,除了在 `AndroidManifest.xml` 中声明读取外部存储的权限之外, 还需特别注意针对特定版本做出相应调整。具体来说: - **添加基本读取权限** 必须向应用清单文件中加入 `<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>` 的声明[^4]。 - **兼容高版本系统的特殊处理** 对于某些更高版本的 Android 系统,即使已授予上述权限也可能遇到无法正常读取的情况。此时建议通过修改 Application 标签属性来解决此问题: ```xml <application android:requestLegacyExternalStorage="true"> ``` #### 获取文件路径 当涉及到具体的文件操作时,开发者可以选择不同的方法来获取所需文件的位置: - **利用内置 API** 可借助 Unity 提供的应用持久化数据路径接口 (`Application.persistentDataPath`) ,该路径通常指向 `/sdcard/Android/data/<package_name>/files` 或者类似的子目录下[^3]。这种方式适用于大多数场景,默认情况下已经具备良好的安全性保障。 - **自定义路径解析** 如果希望突破默认限制范围,则可以在 Project Settings -> Other Settings 将 "Write Permission" 设置为 External (SDCard),从而允许访问更广泛的区域内的资源[^2]。不过需要注意的是这样做可能会带来额外的安全风险以及潜在的隐私政策合规性挑战。 #### 实际编码实现 下面给出一段简单的 C# 示例代码用于展示如何遍历给定路径下的所有图像文件: ```csharp using System.IO; using UnityEngine; public class ImageLoader : MonoBehaviour { void Start() { string path = Path.Combine(Application.persistentDataPath, "Images"); // 假设有一个名为 Images 的文件夹 foreach(string file in Directory.GetFiles(path,"*.png")) { // 支持 png 格式的图片加载 byte[] bytes = File.ReadAllBytes(file); Texture2D texture = new Texture2D(2, 2); if(texture.LoadImage(bytes)){ Debug.Log("成功加载:" + file); }else{ Debug.LogError("失败"); } } } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值