unity从本地选择图片并上传

unity实现打开文件夹选择图片的两种方式:

一、引用System.Windows.Forms

此方法需要在unity的安装目录中找到System.Windows.Forms.dll文件并放在项目的Plugins文件夹中。注意:此方法在打包webgl版本时会报错。

using System.IO;
using System.Windows.Forms;

 public void CreatChartImgPanel()
 {
          OpenFileDialog od = new OpenFileDialog();
           od.Title = "请选择图片";
           od.Multiselect = false;
           od.Filter = "图片文件(*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp";

           if (od.ShowDialog() == DialogResult.OK)
           string TexPath = od.FileName;

            if (!File.Exists(TexPath))
            {
                 Debug.Log("加载失败");
                 return;
            }

            //WWW方式加载图片
            StartCoroutine(WWW_Tex("file://" + TexPath));            
        }

二、引用System.Runtime.InteropServices

此方法PC、webgl均可使用

using System.IO;

using System.Runtime.InteropServices; 

public void CreatChartImgPanel()
        {      

            OpenFileName ofn = new OpenFileName();
            ofn.structSize = Marshal.SizeOf(ofn);
            ofn.filter = "All Files\0*.*\0\0";
            ofn.file = new string(new char[256]);
            ofn.maxFile = ofn.file.Length;
            ofn.fileTitle = new string(new char[64]);
            ofn.maxFileTitle = ofn.fileTitle.Length;
            string path = Application.streamingAssetsPath;
            path = path.Replace('/', '\\');
            ofn.initialDir = path;
            ofn.title = "Open Project";
            ofn.defExt = "JPG";
            //注意 一下项目不一定要全选 但是0x00000008项不要缺少  
            ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;  
            if (WindowDll.GetOpenFileName(ofn))
            {
                Debug.Log("Selected file with full path:" + ofn.file);
            }
            if (ofn.file != "")
            {
                StartCoroutine(WWW_Tex(ofn.file));
            }
        }

 选择完然后加载本地图片

Texture wwwTexture;

IEnumerator WWW_Tex(string url)
{
        WWW www = new WWW(url);
        yield return www;
        if (www.isDone && www.error == null)
        {
                wwwTexture = www.texture;
        }
 }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值