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

좋은 웹페이지 즐겨찾기