• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Unity Android : 读取下载获取移动端 sdcard 路径下的指定文件夹的所有图片的几种方式的

武飞扬头像
仙魁XAN
帮助1

Unity Android 之 读取下载获取移动端 sdcard 路径下的指定文件夹的所有图片的几种方式的简单整理

目录

Unity Android 之 读取下载获取移动端 sdcard 路径下的指定文件夹的所有图片的几种方式的简单整理

一、简单介绍

二、实现原理

三、注意事项

四、简单实现步骤

五、关键代码

附录:

一、不同平台使用宏区分路径加载

二、Unity3D中的资源路径

三、Unity3D各平台路径(包括手机内置存储路径、SD卡等等)


一、简单介绍

Unity中的一些基础知识点,便于后期查看学习。

本节介绍,加载Android手机移动端sdcard 上指定文件上的图片文件的简单方式整理,方法不唯一,仅供参考。

二、实现原理

1、首先 使用 DirectoryInfo 获取该文件夹下的所有文件信息

  1.  
    DirectoryInfo direction = new DirectoryInfo(SD_URL2);
  2.  
    //返回的指定数组 = 返回当前目录的所有文件列表的名字加格式数组
  3.  
    FileInfo[] files = direction.GetFiles("*");

2、然后,根据文件后缀,判断是否是图片,然后进行对应图片的加载

  1.  
    string ext = files[i].Extension;
  2.  
    Debug.Log(" ext " ext);
  3.  
    if (ext.EndsWith("jpg") || ext.EndsWith("png") || ext.EndsWith("jpeg"))

3、然后使用三种方式进行加载

  • WWW w = new WWW(path);
  • UnityWebRequest uwr = new UnityWebRequest(url);
  • 文件读取的方式:FileStream files = new FileStream(imagePath, FileMode.Open);

三、注意事项

1、Android 移动端获取文件夹下的文件信息时,不用添加 "jar:file://" 前缀

2、Android 移动端使用 WWW 或者 UnityWebRequest  加载图片文件时,注意添加 "jar:file://" 前缀

3、Android 移动端使用文件IO读取文件时,不用添加 "jar:file://" 前缀

4、读取 sdcard 文件的时候,注意添加对应权限

5、不同Android手机版本问题,虽然添加了 读取 sdcard 权限,依然没有权限读取,在 AndroidManifest.xml 添加如下进行处理

<application android:requestLegacyExternalStorage="true">

权限报错:Unity: IOException: Permission denied

学新通

6、发现 sdcard 或者 storage/ 或者 storage/emulated/0/ 好似都可以加载根目录文件

四、简单实现步骤

1、新建Unity 工程,简单搭建场景

学新通

2、创建脚本,获取sdcard 对应文件夹下的文件信息,并简单使用三种方式加载对应图片

学新通

3、把脚本添加到场景中

学新通

4、在 PlayerSettings 添加对应sdcard 读写权限,Write Permission 设置为 External(SDCard)

学新通

 5、为了避免可能由于不同 Android 手机版本,可能出现给了权限依旧无法读取的报错

Publishing Setting 勾选 Custom Main Mainifest ,在工程中显示 AndroidManifest.xml,并添加android:requestLegacyExternalStorage="true"

学新通

学新通

学新通

 6、打包运行到Android手机,效果如下

学新通

五、关键代码

1、LoadAndroidImgs.cs

  1.  
    using System;
  2.  
    using System.Collections;
  3.  
    using System.Collections.Generic;
  4.  
    using System.IO;
  5.  
    using UnityEngine;
  6.  
    using UnityEngine.Networking;
  7.  
    using UnityEngine.UI;
  8.  
     
  9.  
    public class LoadAndroidImgs : MonoBehaviour
  10.  
    {
  11.  
    string URL = "file://" "/storage/emulated/0/TestLauncherImages/";
  12.  
    string SD_URL = "/storage/emulated/0/TestLauncherImages/";
  13.  
    string SD_URL2 = "/sdcard/TestLauncherImages/";
  14.  
     
  15.  
    // Start is called before the first frame update
  16.  
    void Start()
  17.  
    {
  18.  
    Load();
  19.  
    GetTexture("https://scpic.chinaz.net/files/pic/pic9/201706/zzpic4354.jpg", (t) => {
  20.  
    GameObject.Find("Canvas/RawImage (1)").GetComponent<RawImage>().texture = t;
  21.  
    });
  22.  
    }
  23.  
     
  24.  
    // Update is called once per frame
  25.  
    void Update()
  26.  
    {
  27.  
     
  28.  
    }
  29.  
     
  30.  
    void Load(){
  31.  
     
  32.  
    DirectoryInfo direction = new DirectoryInfo(SD_URL2);
  33.  
    //返回的指定数组 = 返回当前目录的所有文件列表的名字加格式数组
  34.  
    FileInfo[] files = direction.GetFiles("*");
  35.  
    //存储读取图片的名字字符串
  36.  
    List<string> imageNames = new List<string>();
  37.  
    for (int i = 0; i < files.Length; i )
  38.  
    {
  39.  
    //判断图片的格式字符串是否与指定的字符串不匹配。
  40.  
    if (!files[i].Name.EndsWith(".meta"))
  41.  
    {
  42.  
    //Debug.LogFormat("图片{0}的名字:{1}", i, files[i].FullName);
  43.  
    //添加图片路径和名字字符串到泛型数组
  44.  
    imageNames.Add(files[i].FullName);
  45.  
    Debug.Log(files[i].FullName);
  46.  
    string ext = files[i].Extension;
  47.  
    Debug.Log(" ext " ext);
  48.  
    if (ext.EndsWith("jpg") || ext.EndsWith("png") || ext.EndsWith("jpeg"))
  49.  
    {
  50.  
    //StartCoroutine(doLoadByWWW("jar:file://" files[i].FullName));
  51.  
     
  52.  
    GetTexture("jar:file://" files[i].FullName, (t) => {
  53.  
    GameObject.Find("Canvas/RawImage").GetComponent<RawImage>().texture = t;
  54.  
    });
  55.  
     
  56.  
    //Texture2D tx = new Texture2D(100, 100);
  57.  
    //tx.LoadImage(getImageByte(files[i].FullName));
  58.  
    //GameObject.Find("Canvas/RawImage").GetComponent<RawImage>().texture = (tx);
  59.  
    }
  60.  
    }
  61.  
     
  62.  
     
  63.  
    }
  64.  
     
  65.  
    }
  66.  
     
  67.  
    IEnumerator doLoadByWWW(String path)
  68.  
    {
  69.  
     
  70.  
    WWW w = new WWW(path);
  71.  
     
  72.  
    yield return w;
  73.  
     
  74.  
    if (w.isDone)
  75.  
    {
  76.  
    Sprite sprite = Sprite.Create(w.texture, new Rect(0, 0, w.texture.width, w.texture.height), new Vector2(0.5f, 0.5f));
  77.  
     
  78.  
    GameObject.Find("Canvas/Image").GetComponent<Image>().sprite = sprite;
  79.  
     
  80.  
    }
  81.  
    }
  82.  
     
  83.  
    /// <summary>
  84.  
    /// 请求图片
  85.  
    /// </summary>
  86.  
    /// <param name="url">图片地址,like 'http://www.my-server.com/image.png '</param>
  87.  
    /// <param name="action">请求发起后处理回调结果的委托,处理请求结果的图片</param>
  88.  
    /// <returns></returns>
  89.  
    public void GetTexture(string url, Action<Texture2D> actionResult)
  90.  
    {
  91.  
    StartCoroutine(_GetTexture(url, actionResult));
  92.  
    }
  93.  
     
  94.  
    /// <summary>
  95.  
    /// 请求图片
  96.  
    /// </summary>
  97.  
    /// <param name="url">图片地址,like 'http://www.my-server.com/image.png '</param>
  98.  
    /// <param name="action">请求发起后处理回调结果的委托,处理请求结果的图片</param>
  99.  
    /// <returns></returns>
  100.  
    IEnumerator _GetTexture(string url, Action<Texture2D> actionResult)
  101.  
    {
  102.  
    UnityWebRequest uwr = new UnityWebRequest(url);
  103.  
    DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
  104.  
    uwr.downloadHandler = downloadTexture;
  105.  
    yield return uwr.SendWebRequest();
  106.  
    Texture2D t = null;
  107.  
    if (!(uwr.isNetworkError || uwr.isHttpError))
  108.  
    {
  109.  
    t = downloadTexture.texture;
  110.  
    }
  111.  
    else
  112.  
    {
  113.  
    Debug.Log("下载失败,请检查网络,或者下载地址是否正确: " uwr.error);
  114.  
    }
  115.  
     
  116.  
    if (actionResult != null)
  117.  
    {
  118.  
    actionResult(t);
  119.  
    }
  120.  
    }
  121.  
     
  122.  
    /// <summary>
  123.  
    /// 根据图片路径返回图片的字节流byte[]
  124.  
    /// </summary>
  125.  
    /// <param name="imagePath">图片路径</param>
  126.  
    /// <returns>返回的字节流</returns>
  127.  
    private static byte[] getImageByte(string imagePath)
  128.  
    {
  129.  
    FileStream files = new FileStream(imagePath, FileMode.Open);
  130.  
    byte[] imgByte = new byte[files.Length];
  131.  
    files.Read(imgByte, 0, imgByte.Length);
  132.  
    files.Close();
  133.  
    return imgByte;
  134.  
    }
  135.  
     
  136.  
    }

2、AndroidManifest.xml

  1.  
    <?xml version="1.0" encoding="utf-8"?>
  2.  
    <manifest
  3.  
    xmlns:android="http://schemas.android.com/apk/res/android"
  4.  
    package="com.unity3d.player"
  5.  
    xmlns:tools="http://schemas.android.com/tools">
  6.  
     
  7.  
    <application android:requestLegacyExternalStorage="true">
  8.  
    <activity android:name="com.unity3d.player.UnityPlayerActivity"
  9.  
    android:theme="@style/UnityThemeSelector">
  10.  
    <intent-filter>
  11.  
    <action android:name="android.intent.action.MAIN" />
  12.  
    <category android:name="android.intent.category.LAUNCHER" />
  13.  
    </intent-filter>
  14.  
    <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
  15.  
    </activity>
  16.  
    </application>
  17.  
    </manifest>

附录:

一、不同平台使用宏区分路径加载

  1.  
    #if UNITY_EDITOR
  2.  
    filepath = Application.dataPath "/StreamingAssets";
  3.  
    #elif UNITY_IOS || UNITY_IPHONE
  4.  
    filepath = "file://" Application.streamingAssetsPath;
  5.  
    #elif UNITY_ANDROID
  6.  
    filepath = "jar:file://" Application.dataPath "!/assets";
  7.  
    #endif

二、Unity3D中的资源路径

  • Application.dataPath    此属性用于返回程序的数据文件所在文件夹的路径。例如在Editor中就是Assets了。
  • Application.streamingAssetsPath    此属性用于返回流数据的缓存目录,返回路径为相对路径,适合设置一些外部数据文件的路径。
  • Application.persistentDataPath    此属性用于返回一个持久化数据存储目录的路径,可以在此路径下存储一些持久化的数据文件。
  • Application.temporaryCachePath    此属性用于返回一个临时数据的缓存目录。
     

三、Unity3D各平台路径(包括手机内置存储路径、SD卡等等)

关于Unity3D在各平台上的路径问题,网上有好多的资料,如下是比较好的参考资料:

1、http://www.manew.com/thread-23491-1-1.html

2、#你好Unity3D#手机上的路径(来自我的长微博) | 雨松MOMO程序研究院

  这里我不详细解释和路径的用法,只把各个路径对应的位置和访问方式总结一下。

1、Resources路径

  Resources文件夹是Unity里自动识别的一种文件夹,可在Unity编辑器的Project窗口里创建,并将资源放置在里面。Resources文件夹下的资源不管是否有用,全部会打包进.apk或者.ipa,并且打包时会将里面的资源压缩处理。加载方法是Resources.Load<T>(文件名),需要注意:文件名不包括扩展名,打包后不能更改Resources下的资源内容,但是从Resources文件夹中加载出来的资源可以更改。

2、Application.dataPath路径

  这个属性返回的是程序的数据文件所在文件夹的路径,例如在Editor中就是项目的Assets文件夹的路径,通过这个路径可以访问项目中任何文件夹中的资源,但是在移动端它是完全没用。

3、Application.streamingAssetsPath路径

  这个属性用于返回流数据的缓存目录,返回路径为相对路径,适合设置一些外部数据文件的路径。在Unity工程的Assets目录下起一个名为“StreamingAssets”的文件夹即可,然后用Application.streamingAssetsPath访问,这个文件夹中的资源在打包时会原封不动的打包进去,不会压缩,一般放置一些资源数据。在PC/MAC中可实现对文件的“增删改查”等操作,但在移动端是一个只读路径。

4、Application.persistentDataPath路径(推荐使用)

  此属性返回一个持久化数据存储目录的路径,可以在此路径下存储一些持久化的数据文件。这个路径可读、可写,但是只能在程序运行时才能读写操作,不能提前将数据放入这个路径。在IOS上是应用程序的沙盒,可以被iCloud自动备份,可以通过同步推送一类的助手直接取出文件;在Android上的位置是根据Project Setting里设置的Write Access路径,可以设置是程序沙盒还是sdcard,注意:如果在Android设置保存在沙盒中,那么就必须root以后才能用电脑取出文件,因此建议写入sdcard里。一般情况下,建议将获得的文件保存在这个路径下,例如可以从StreamingAsset中读取的二进制文件或者从AssetBundle读取的文件写入PersistentDatapath。

5、Application.temporaryCachePath路径

  此属性返回一个临时数据的缓存目录,跟Application.persistentDataPath类似,但是在IOS上不能被自动备份。

6、/sdcard/..路径

  表示Android手机的SD卡根目录。

7、/storage/emulated/0/..路径(这个路径我查找了好久……)

  表示Android手机的内置存储根目录。

  以上各路径中的资源加载方式都可以用WWW类加载,但要注意各个平台路径需要加的访问名称,例如Android平台的路径前要加"jar:file://",其他平台使用"file://"。以下是各路径在各平台中的具体位置信息:

Android平台

Application.dataPath :  /data/app/xxx.xxx.xxx.apk

Application.streamingAssetsPath :  jar:file:///data/app/xxx.xxx.xxx.apk/!/assets

Application.persistentDataPath :  /data/data/xxx.xxx.xxx/files

Application.temporaryCachePath :  /data/data/xxx.xxx.xxx/cache

IOS平台

Application.dataPath :                    Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/Data

Application.streamingAssetsPath : Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/Data/Raw

Application.persistentDataPath :    Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/Documents

Application.temporaryCachePath : Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/Library/Caches

Windows Web Player

Application.dataPath :  file:///D:/MyGame/WebPlayer (即导包后保存的文件夹,html文件所在文件夹)

Application.streamingAssetsPath : 

Application.persistentDataPath : 

Application.temporaryCachePath : 

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgikbak
系列文章
更多 icon
同类精品
更多 icon
继续加载