Unity 로 컬 그림 가 져 오기 및 저장 후 사용
9607 단어 Unity3D
우선,로 컬 디 렉 터 리 를 열 고 경 로 를 가 져 옵 니 다:
///
///
///
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);
다음 에 폴 더 의 그림 을 읽 고 사전 에 저장 하 며 출력 rollview 에 grid 형식 으로 저장 하여 선택 적 으로 사용 합 니 다.
전체 코드 는 다음 과 같 습 니 다.
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Unity 공부 일지~블렌드 셰이프 조작 방법 그 ①게임을 만들고 싶다 ~라고 생각하고 마지막 날부터 Unity를 만지기 시작했습니다 HITOMI2236입니다. 이번 블렌드 셰이프에 대해 조사했으므로 여기에 기록하려고 합니다. 개인용 메모입니다만, 만약 같은 곳에서 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.