【Unity】PC读取本地图片文件

首先,配置一个打开文件日志类,代码如下:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileDlg
{
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String initialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;
}

public class OpenFileDialog
{
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] OpenFileDlg ofd);
    public static bool GetOpenFileName1([In, Out] OpenFileDlg ofd)
    {
        return GetOpenFileName(ofd);
    }
}

然后,我这里是使用了一个静态管理器来管理加载图片

public class OpenFileMgr :MonoBehaviour
{
    private static OpenFileMgr instance;
    public static OpenFileMgr GetInstance()
    {
        if (instance==null)
        {
            GameObject obj = new GameObject("OpenFileMgr");
            
            instance = obj.AddComponent<OpenFileMgr>();
            return instance;
        }
        return instance;

    }

    #region 打开文件夹
    /// <summary>
    /// 打开资源管理器界面
    /// </summary>
    public void Openfile()
    {

        OpenFileDlg pth = new OpenFileDlg();
        pth.structSize = System.Runtime.InteropServices.Marshal.SizeOf(pth);
       
        //加载图片文件
        pth.filter = "图片文件(*.jpg*.png)\0*.jpg;*.png";
         
        pth.file = new string(new char[256]);
        pth.maxFile = pth.file.Length;
        pth.fileTitle = new string(new char[64]);
        pth.maxFileTitle = pth.fileTitle.Length;
        pth.initialDir = Application.streamingAssetsPath.Replace('/', '\\');  // default path
        pth.title = "选择项目json";
        pth.defExt = "JPG";//显示文件类型
        pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
        if (OpenFileDialog.GetOpenFileName(pth))
        {
            string filepath = pth.file;//选择的文件路径;

            DirectoryInfo i = new DirectoryInfo(filepath);

            //上级目录
            string path = i.Parent.FullName;//返回文件的上级目录
            Debug.Log(path);//文件目录父目录
            Debug.Log(i.FullName);//文件路径全
            try
            {
            StartCoroutine("LoadIamge", i.FullName);
                
            }
            catch (Exception)
            {

                throw;
            }
            
        }
    }
    #endregion

    //显示加载的图片
    public Image image;
    /// <summary>
    /// 加载本地图片
    /// </summary>
    /// <param name="path">本地文件路径</param>
    /// <returns></returns>
    IEnumerator LoadIamge(string path)
    {   //计算加载用时    
        double startTime = (double)Time.time;


        WWW www = new WWW("file:///" + path);
        yield return www;
        if (www != null && string.IsNullOrEmpty(www.error))
        {
            //获取Texture
            Texture2D texture = www.texture;
            //更多操作...
            //直接将选择图保存
            byte[] bytes = texture.EncodeToJPG();
            //测试地址
            //string filename = @"G:\wenshuxin\BackGround\6.jpg";
            System.IO.File.WriteAllBytes(path, bytes);
            //根据获取的Texture创建一个sprite
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            //将sprite显示在图片上
            //image.sprite = sprite;
            //图片设置为原始尺寸
            //image.SetNativeSize();
            image.sprite= sprite;

            //计算加载用时
            startTime = (double)Time.time - startTime;
            Debug.Log("WWW加载用时:" + startTime);
        }
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Unity可以使用C#语言读取本地文件,包括本地的EXC文件。 下面是读取本地EXC文件的一些基本步骤: 1. 首先在Unity中创建一个新的C#脚本,然后将其命名为“ExcelReader”(或者你喜欢的其他名称)。 2. 在该脚本中添加以下代码,以便引入ExcelDataReader和System.Data库: ```csharp using UnityEngine; using System.IO; using ExcelDataReader; using System.Data; ``` 3. 在ExcelDataReader官网下载ExcelDataReader和ExcelDataReader.DataSet库的NuGet包,并将它们添加到Unity项目中。此步骤需要使用Visual Studio或者其他适当的IDE。 4. 在ExcelDataReader命名空间下创建一个新的ExcelReader类。在该类中添加以下代码: ```csharp public static DataSet LoadExcelFile(string filePath) { FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read); IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); DataSet result = excelReader.AsDataSet(); excelReader.Close(); return result; } ``` 5. 通过调用LoadExcelFile方法来读取本地Excel文件。以下代码演示了如何使用该方法: ```csharp DataSet dataSet = ExcelReader.LoadExcelFile(Application.dataPath + "/ExcelFiles/test.xlsx"); DataTableCollection tableCollection = dataSet.Tables; foreach (DataTable table in tableCollection) { for (int i = 0; i < table.Rows.Count; i++) { DataRow row = table.Rows[i]; Debug.Log(row[0].ToString() + " " + row[1].ToString() + " " + row[2].ToString()); } } ``` 这将从Assets文件夹中的ExcelFiles文件夹中读取名为“test.xlsx”的文件,并在控制台中输出所有单元格的值。 希望这可以帮助你读取本地EXC文件。如果你有任何其他问题,请随时问我。 ### 回答2: Unity提供了一种方法来读取本地的Excel文件。下面是一个简单的步骤来实现这一过程: 1. 首先,确保你已经将Excel文件放置在Unity项目的资源文件夹中。可以将Excel文件直接拖放到Unity项目资源文件夹中,或者将其复制到该文件夹中。 2. 打开Unity编辑器,创建一个新的C#脚本。 3. 在脚本中,使用Unity提供的API来读取Excel文件。可以使用ExcelDataReader等第三方库来实现这一功能。可以通过使用NuGet包管理器将ExcelDataReader添加到Unity项目中。 4. 导入所需的命名空间,并使用相应的类和方法来加载并解析Excel文件。例如,可以使用ExcelDataReader提供的ExcelReader类来读取Excel文件。 5. 使用ExcelReader类初始化一个Excel文件,并指定要读取的工作表。可以使用索引或工作表名称来指定要读取的工作表。 6. 使用循环逐行读取工作表中的数据。可以使用类似的循环结构来遍历每一行,并使用该行的索引来访问特定单元格中的数据。 7. 在读取完数据后,可以根据需要对读取到的数据进行处理和使用。例如,可以将数据存储在一个数组或列表中,或者将其用于进一步的计算和操作。 需要注意的是,Unity默认情况下不支持读取Excel文件,因此需要使用适当的第三方库来解析和读取Excel文件。此外,注意在读取Excel文件时,不同的Excel文件类型(.xls或.xlsx)可能需要使用不同的库或不同的方法来正确读取数据。 这些是一些基本的步骤来读取本地Excel文件,具体实现的步骤可能因使用的库和文件类型而有所不同。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值