unity打開本地文件 代碼如下
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; /// <summary> /// 數據接收類 /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class FileOpenDialog{ 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 DialogShow { [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)] public static extern bool GetOpenFileName([In, Out]FileOpenDialog dialog); //這個方法名稱必須為GetOpenFileName } public class OpenFileByWin32 : MonoBehaviour { //打開文件 public void OpenFile() { FileOpenDialog dialog = new FileOpenDialog(); dialog.structSize = Marshal.SizeOf(dialog); // dialog.filter = "exe files\0*.exe\0All Files\0*.*\0\0"; dialog.filter = "圖片文件(*.png*.jpg)\0*.png;*.jpg"; dialog.file = new string(new char[256]); dialog.maxFile = dialog.file.Length; dialog.fileTitle = new string(new char[64]); dialog.maxFileTitle = dialog.fileTitle.Length; dialog.initialDir = UnityEngine.Application.dataPath; //默認路徑 dialog.title = "Open File Dialog"; dialog.defExt = "png";//顯示文件的類型 //注意一下項目不一定要全選 但是0x00000008項不要缺少 dialog.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008; if (DialogShow.GetOpenFileName(dialog)) { if (dialog.file!=null) { Structure_RenZhi.instacnce.Chuandong(dialog.file);//dialog.file本地圖片的地址 } else { return; } } } }
下面是把獲取到圖片地址的文件流轉換成Image
public Image image;
public string url; //把路徑圖片轉換成 Image public void Chuandong(string path) { image.sprite = ChangeToSprite(ByteToTex2d(byteToImage(path))); url = path; print(url); } //根據圖片路徑返回圖片的字節流byte[] public static byte[] byteToImage(string path) { FileStream files = new FileStream(path, FileMode.Open); byte[] imgByte = new byte[files.Length]; files.Read(imgByte, 0, imgByte.Length); files.Close(); return imgByte; } //根據字節流轉換成圖片 public static Texture2D ByteToTex2d(byte[] bytes) { int w = 500; int h = 500; Texture2D tex = new Texture2D(w, h); tex.LoadImage(bytes); return tex; } //轉換為Image private Sprite ChangeToSprite(Texture2D tex) { Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f)); return sprite; }
然后在把獲取到的圖片路徑 轉換成文件流 在保存成圖片
// 開啟協程就可以保存成圖片了 IEnumerator DownSprite() { yield return new WaitForSeconds(0); Texture2D tex = ByteToTex2d(byteToImage(url)); //保存本地 Byte[] bytes = tex.EncodeToPNG(); File.WriteAllBytes(Application.streamingAssetsPath + "/DataerTion/"+ filed_photo.text+".png", bytes); //filed_photo.text 是保存圖片的名字 # if UNITY_EDITOR AssetDatabase.Refresh(); //刷新Editor 不刷新顯示不出來 #endif }
下面是使用保存的圖片顯示在ui上面 怎么使用具體看需要 可以拉幾個UI(如下圖)試一下 看看效果
下面上代碼
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.UI; /// <summary> /// 切換圖片顯示, 讀取unity本地圖片文件顯示在ui /// </summary> public class Cut_Photo : MonoBehaviour { public Dictionary<int, Sprite> spriteDic = new Dictionary<int, Sprite>(); public Button button_zuo; public Button button_you; public Image image; private int aa=0; // Start is called before the first frame update void Start() { GetTexture(); // image = this.transform.GetComponent<Image>(); image.sprite =spriteDic[aa]; Debug.Log(spriteDic.Count); button_zuo.onClick.AddListener(delegate { if (aa !=0) { aa--; } else { aa = (spriteDic.Count - 1); } image.sprite = spriteDic[aa]; }); button_you.onClick.AddListener(delegate { if (aa != (spriteDic.Count-1)) { aa++; } else { aa = 0; } image.sprite = spriteDic[aa]; }); } //獲取文件里面的圖片 public void GetTexture() { DirectoryInfo dir = new DirectoryInfo(Application.streamingAssetsPath + "/DataerTion"); FileInfo[] filess = dir.GetFiles("*.png");//獲取所有文件的信息 int i = 0; foreach (FileInfo file in filess) { FileStream fs = new FileStream(Application.streamingAssetsPath + "/DataerTion/" + file.Name, FileMode.Open); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); Texture2D tex = new Texture2D(2, 2); tex.LoadImage(buffer); tex.Apply(); spriteDic.Add(i, ChangeToSprite(tex)); i++; } } //轉換為Image private Sprite ChangeToSprite(Texture2D tex) { Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f)); return sprite; } // Update is called once per frame void Update() { } }
//指定一張圖片顯示在UI上面 public void GetTexTure(string spriptname,Image sprit ) { string picpath = Application.streamingAssetsPath + "/DataerTion/" + spriptname.ToString() + ".png"; if (File.Exists(picpath)) { byte[] bt = File.ReadAllBytes(picpath); Texture2D t2d = new Texture2D(1920, 1080); t2d.LoadImage(bt); Sprite sprite = Sprite.Create(t2d, new Rect(0, 0, t2d.width, t2d.height), Vector2.zero); sprit.sprite = sprite; } }
//指定多張圖片的 public void GetTexTure1(string spriptname) { for (int i = 0; i < 10; i++) { string picpath = Application.streamingAssetsPath + "/DataerTion/" + spriptname.ToString()+i+ ".png"; if (File.Exists(picpath)) { byte[] bt = File.ReadAllBytes(picpath); Texture2D t2d = new Texture2D(1920, 1080); t2d.LoadImage(bt); Sprite sprite = Sprite.Create(t2d, new Rect(0, 0, t2d.width, t2d.height), Vector2.zero); //sprit.sprite = sprite; spriteDic.Add(i, sprite); } } }
本次就這么多,謝謝大家,有需要會繼續補充