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

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

目录

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

一、简单介绍

二、实现原理

三、注意事项

四、简单实现步骤

五、关键代码

附录:

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

二、Unity3D中的资源路径

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


一、简单介绍

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

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

二、实现原理

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

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

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

         string ext = files[i].Extension;
         Debug.Log("  ext  " + ext);
         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

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class LoadAndroidImgs : MonoBehaviour
{
    string URL = "file://" + "/storage/emulated/0/TestLauncherImages/";
    string SD_URL =  "/storage/emulated/0/TestLauncherImages/";
    string SD_URL2 = "/sdcard/TestLauncherImages/";

    // Start is called before the first frame update
    void Start()
    {
        Load();
        GetTexture("https://scpic.chinaz.net/files/pic/pic9/201706/zzpic4354.jpg", (t) => {
            GameObject.Find("Canvas/RawImage (1)").GetComponent<RawImage>().texture = t;
        });
    }

    // Update is called once per frame
    void Update()
    {

    }

    void Load(){

        DirectoryInfo direction = new DirectoryInfo(SD_URL2);
        //返回的指定数组 = 返回当前目录的所有文件列表的名字加格式数组 
        FileInfo[] files = direction.GetFiles("*");
        //存储读取图片的名字字符串
        List<string> imageNames = new List<string>();
        for (int i = 0; i < files.Length; i++)
        {
            //判断图片的格式字符串是否与指定的字符串不匹配。
            if (!files[i].Name.EndsWith(".meta"))
            {
                //Debug.LogFormat("图片{0}的名字:{1}", i, files[i].FullName);
                //添加图片路径和名字字符串到泛型数组
                imageNames.Add(files[i].FullName);
                Debug.Log(files[i].FullName);
                string ext = files[i].Extension;
                Debug.Log("  ext  " + ext);
                if (ext.EndsWith("jpg") || ext.EndsWith("png") || ext.EndsWith("jpeg"))
                {
                    //StartCoroutine(doLoadByWWW("jar:file://" + files[i].FullName));

                    GetTexture("jar:file://"+files[i].FullName, (t) => {
                        GameObject.Find("Canvas/RawImage").GetComponent<RawImage>().texture = t;
                    });

                     //Texture2D tx = new Texture2D(100, 100);
                     //tx.LoadImage(getImageByte(files[i].FullName));
                     //GameObject.Find("Canvas/RawImage").GetComponent<RawImage>().texture = (tx);
                }
            }

            
        }

    }

    IEnumerator doLoadByWWW(String path)
    {

        WWW w = new WWW(path);

        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/Image").GetComponent<Image>().sprite = sprite;

        }
    }

    /// <summary>
    /// 请求图片
    /// </summary>
    /// <param name="url">图片地址,like 'http://www.my-server.com/image.png '</param>
    /// <param name="action">请求发起后处理回调结果的委托,处理请求结果的图片</param>
    /// <returns></returns>
    public void GetTexture(string url, Action<Texture2D> actionResult)
    {
        StartCoroutine(_GetTexture(url, actionResult));
    }

    /// <summary>
    /// 请求图片
    /// </summary>
    /// <param name="url">图片地址,like 'http://www.my-server.com/image.png '</param>
    /// <param name="action">请求发起后处理回调结果的委托,处理请求结果的图片</param>
    /// <returns></returns>
    IEnumerator _GetTexture(string url, Action<Texture2D> actionResult)
    {
        UnityWebRequest uwr = new UnityWebRequest(url);
        DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
        uwr.downloadHandler = downloadTexture;
        yield return uwr.SendWebRequest();
        Texture2D t = null;
        if (!(uwr.isNetworkError || uwr.isHttpError))
        {
            t = downloadTexture.texture;
        }
        else
        {
            Debug.Log("下载失败,请检查网络,或者下载地址是否正确: "+ uwr.error);
        }

        if (actionResult != null)
        {
            actionResult(t);
        }
    }

    /// <summary>  
    /// 根据图片路径返回图片的字节流byte[]  
    /// </summary>  
    /// <param name="imagePath">图片路径</param>  
    /// <returns>返回的字节流</returns>  
    private static byte[] getImageByte(string imagePath)
    {
        FileStream files = new FileStream(imagePath, FileMode.Open);
        byte[] imgByte = new byte[files.Length];
        files.Read(imgByte, 0, imgByte.Length);
        files.Close();
        return imgByte;
    }

}

2、AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.unity3d.player"
    xmlns:tools="http://schemas.android.com/tools">
	
	<application android:requestLegacyExternalStorage="true">
        <activity android:name="com.unity3d.player.UnityPlayerActivity"
                  android:theme="@style/UnityThemeSelector">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>
    </application>
</manifest>

附录:

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

#if UNITY_EDITOR
        filepath = Application.dataPath + "/StreamingAssets";
#elif UNITY_IOS || UNITY_IPHONE
        filepath = "file://" + Application.streamingAssetsPath;
#elif UNITY_ANDROID
        filepath = "jar:file://"  + Application.dataPath + "!/assets";
#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 : 

  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仙魁XAN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值