日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Unity获取本地图片并保存后使用

發布時間:2024/1/18 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Unity获取本地图片并保存后使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文思路為,打開本地文件夾,獲取到圖片,然后存到相對路徑下,再次調用。

首先,打開本地目錄,獲取路徑:

?

/// <summary>/// 獲得路徑/// </summary>private void GetPather(){OpenFileName openFileName = new OpenFileName();openFileName.structSize = Marshal.SizeOf(openFileName);openFileName.filter = "圖片文件(*.jpg,*.png,*.bmp)\0*.jpg;*.png;*.bmp";openFileName.file = new string(new char[256]);openFileName.maxFile = openFileName.file.Length;openFileName.fileTitle = new string(new char[64]);openFileName.maxFileTitle = openFileName.fileTitle.Length;openFileName.initialDir = Application.streamingAssetsPath.Replace('/', '\\');//默認路徑openFileName.title = "選擇圖片";openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;if (LocalDialog.GetSaveFileName(openFileName)){texPath = openFileName.file;FileStreamLoadTexture();}}

然后通過獲取的這個路徑讀取圖片:

/// <summary>/// 文件流加載圖片/// </summary>private void FileStreamLoadTexture(){//通過路徑加載本地圖片FileStream fs = new FileStream(texPath, FileMode.Open);byte[] buffer = new byte[fs.Length];fs.Read(buffer, 0, buffer.Length);fs.Close();originalTex = new Texture2D(2, 2);var iSLoad = originalTex.LoadImage(buffer);originalTex.Apply();if (!iSLoad){Debug.Log("Texture存在但生成Texture失敗");}GetTexture();File.WriteAllBytes(Application.dataPath + "\\Pictures//texture" + (sprites.Count).ToString() + ".png", originalTex.EncodeToPNG());}

存取圖片時,由于發布需求,所以采用了自建文件夾的方式:

?

?

string dirPath = Application.dataPath + "/" + "Pictures";DirectoryInfo mydir = new DirectoryInfo(dirPath);if (!mydir.Exists)Directory.CreateDirectory(dirPath);

后面,再讀取文件夾中的圖片,存到字典,以grid形式存放于輸出rollview中,用于選擇使用。

?

整體代碼如下:

GetPicture:

?

using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.IO;using UnityEngine; using UnityEngine.UI;#region OpenFileName數據接收類 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class OpenFileName {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; } #endregion#region 系統函數調用類 public class LocalDialog {//鏈接指定系統函數 打開文件對話框[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);public static bool GetOFN([In, Out] OpenFileName ofn){return GetOpenFileName(ofn);}//鏈接指定系統函數 另存為對話框[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]public static extern bool GetSaveFileName([In, Out] OpenFileName ofn);public static bool GetSFN([In, Out] OpenFileName ofn){return GetSaveFileName(ofn);} } #endregion#region 入口類 public class GetPicture : MonoBehaviour {private PinTuGameObjectManger gom;private string texPath;private Texture2D originalTex;//private int count;private object[] pictures;private Dictionary<int, Sprite> sprites = new Dictionary<int, Sprite>();private void Start(){gom = gameObject.GetComponent<PinTuGameObjectManger>();gom.btnLoad.onClick.AddListener(OnLoadButtonClick);gom.btnSelect.onClick.AddListener(ReadPicture);//PlayerPrefs.DeleteAll();//count = PlayerPrefs.GetInt("Count",0);string dirPath = Application.dataPath + "/" + "Pictures";DirectoryInfo mydir = new DirectoryInfo(dirPath);if (!mydir.Exists)Directory.CreateDirectory(dirPath);GetTexture();}/// <summary>/// 加載圖片按鈕點擊事件/// </summary>private void OnLoadButtonClick(){GetPather();gom.picForSelect.SetActive(false);}/// <summary>/// 獲得路徑/// </summary>private void GetPather(){OpenFileName openFileName = new OpenFileName();openFileName.structSize = Marshal.SizeOf(openFileName);openFileName.filter = "圖片文件(*.jpg,*.png,*.bmp)\0*.jpg;*.png;*.bmp";openFileName.file = new string(new char[256]);openFileName.maxFile = openFileName.file.Length;openFileName.fileTitle = new string(new char[64]);openFileName.maxFileTitle = openFileName.fileTitle.Length;openFileName.initialDir = Application.streamingAssetsPath.Replace('/', '\\');//默認路徑openFileName.title = "選擇圖片";openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;if (LocalDialog.GetSaveFileName(openFileName)){texPath = openFileName.file;FileStreamLoadTexture();}}/// <summary>/// 文件流加載圖片/// </summary>private void FileStreamLoadTexture(){//通過路徑加載本地圖片FileStream fs = new FileStream(texPath, FileMode.Open);byte[] buffer = new byte[fs.Length];fs.Read(buffer, 0, buffer.Length);fs.Close();originalTex = new Texture2D(2, 2);var iSLoad = originalTex.LoadImage(buffer);originalTex.Apply();if (!iSLoad){Debug.Log("Texture存在但生成Texture失敗");}GetTexture();File.WriteAllBytes(Application.dataPath + "\\Pictures//texture" + (sprites.Count).ToString() + ".png", originalTex.EncodeToPNG());}/// <summary>/// 讀取圖片/// </summary>private void ReadPicture(){DisplayToScroll();gom.picForSelect.SetActive(true);}/// <summary>/// 轉換為Sprite/// </summary>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;}/// <summary>/// 顯示在左側/// </summary>private void DisplayToScroll(){for (int i = 0; i < gom.parent.transform.childCount; i++){Destroy(gom.parent.transform.GetChild(i).gameObject);}GetTexture();for (int j = 0; j < sprites.Count; j++){GameObject go = new GameObject("img" + j.ToString(), typeof(Image));go.GetComponent<Image>().sprite = sprites[j];go.AddComponent<PictureSelect>();go.transform.parent = gom.parent.transform;}}private void GetTexture(){sprites.Clear();DirectoryInfo dir = new DirectoryInfo(Application.dataPath + "/Pictures");FileInfo[] files = dir.GetFiles("*.png"); //獲取所有文件信息 int i = 0;foreach (FileInfo file in files){FileStream fs = new FileStream(Application.dataPath + "/Pictures/" + 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();sprites.Add(i, ChangeToSprite(tex));i++;}} } #endregion

PictureSelect:

?

?

using UnityEngine;public class PictureSelect: MonoBehaviour {private PinTuGameObjectManger gom;private void Start () {gom = GameObject.FindGameObjectWithTag("Empty").GetComponent<PinTuGameObjectManger>();gameObject.AddComponent<UnityEngine.UI.Button>().onClick.AddListener(() => {gom.picForSelect.SetActive(false);gom.displayImage.GetComponent<UnityEngine.UI.Image>().sprite = gameObject.GetComponent<UnityEngine.UI.Image>().sprite;});} }

PinTuGameObjectManger:

?

?

using UnityEngine; using UnityEngine.UI;public class PinTuGameObjectManger: MonoBehaviour {public Button btnLoad;public Button btnSelect;public GameObject picForSelect;public GameObject parent;public Image displayImage; }

?


demo鏈接:云盤下載

?

?

密碼:gbuo

總結

以上是生活随笔為你收集整理的Unity获取本地图片并保存后使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。