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

  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

末零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值