本文思路为,打开本地文件夹,获取到图片,然后存到相对路径下,再次调用。
首先,打开本地目录,获取路径:
///
/// 获得路径
///
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();
}
}
然后通过获取的这个路径读取图片:
///
/// 文件流加载图片
///
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 sprites = new Dictionary();
private void Start()
{
gom = gameObject.GetComponent();
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();
}
///
/// 加载图片按钮点击事件
///
private void OnLoadButtonClick()
{
GetPather();
gom.picForSelect.SetActive(false);
}
///
/// 获得路径
///
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();
}
}
///
/// 文件流加载图片
///
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());
}
///
/// 读取图片
///
private void ReadPicture()
{
DisplayToScroll();
gom.picForSelect.SetActive(true);
}
///
/// 转换为Sprite
///
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;
}
///
/// 显示在左侧
///
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().sprite = sprites[j];
go.AddComponent();
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();
gameObject.AddComponent().onClick.AddListener(() => {
gom.picForSelect.SetActive(false);
gom.displayImage.GetComponent().sprite = gameObject.GetComponent().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