Unity 浏览本地图片并加载

在开发过程中,经常会有在软件中浏览本地文件的需求,今天就在Unity中实现一下浏览本地图片并加载的小功能。
功能预览:
在这里插入图片描述
其实实现起来很方便。注释中都有代码,只需要两个代码,一个是调用系统的窗口,一个是加载图片

using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;

/// <summary>
/// 调用系统的窗口,数据接收类
/// </summary>
[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;
}

public class WindowDll
{
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
    public static bool GetOpenFileName1([In, Out] OpenFileName ofn)
    {
        return GetOpenFileName(ofn);
    }
}
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.Reflection;
using UnityEngine.UI;

public class LoadImage : MonoBehaviour
{

    public Image image;

    public Texture buttonTexture;


    // Update is called once per frame
    void Update()
    {

    }

    void OnGUI()
    {
        //设置按钮文字的大小,颜色,背景等
        GUIStyle fontStyle = new GUIStyle();
        fontStyle.alignment = TextAnchor.MiddleCenter;
        fontStyle.fontSize = 50;
        fontStyle.normal.textColor = Color.white;
        fontStyle.normal.background = (Texture2D)buttonTexture;


        if (GUI.Button(new Rect(10, 10, 300, 100), "Open",fontStyle))
        {
            OpenFileName ofn = new OpenFileName();
            ofn.structSize = Marshal.SizeOf(ofn);
            ofn.filter = "图片文件(*.jpg*.png)\0*.jpg;*.png";
            ofn.file = new string(new char[256]);
            ofn.maxFile = ofn.file.Length;
            ofn.fileTitle = new string(new char[64]);
            ofn.maxFileTitle = ofn.fileTitle.Length;
            //默认路径
            string path = Application.streamingAssetsPath;
            path = path.Replace('/', '\\');
            //默认路径
            //ofn.initialDir = "G:\\wenshuxin\\test\\HuntingGame_Test\\Assets\\StreamingAssets";
            ofn.initialDir = path;           
            ofn.title = "Open Project";
            ofn.defExt = "JPG";//显示文件的类型
            //注意 一下项目不一定要全选 但是0x00000008项不要缺少
            ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR
            //点击Windows窗口时开始加载选中的图片
            if (WindowDll.GetOpenFileName(ofn))
            {
                Debug.Log("Selected file with full path: " + ofn.file);
                StartCoroutine(Load(ofn.file));
            }
        }
    }

   
    /// <summary>
    /// 加载本地图片
    /// </summary>
    /// <param name="path">本地文件路径</param>
    /// <returns></returns>
    IEnumerator Load(string path)
    {   //计算加载用时    
        double startTime = (double)Time.time; 
        

        WWW www = new WWW("file:///" + path);
        yield return www;
        if (www != null && string.IsNullOrEmpty(www.error))
        {
            //获取Texture
            Texture2D texture = www.texture;
            //更多操作...
            //直接将选择图保存
            byte[] bytes = texture.EncodeToJPG();
            //测试地址
            //string filename = @"G:\wenshuxin\BackGround\6.jpg";
            System.IO.File.WriteAllBytes(path, bytes);
            //根据获取的Texture创建一个sprite
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            //将sprite显示在图片上
            image.sprite = sprite;
            //图片设置为原始尺寸
            image.SetNativeSize();


            //计算加载用时
            startTime = (double)Time.time - startTime;
            Debug.Log("WWW加载用时:" + startTime);
        }
    }
   
}

  • 7
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
### 回答1: 在Unity,我们可以通过以下步骤将服务器上的图片保存到本地并加载: 1. 首先,我们需要使用Unity的WebRequest类来从服务器上下载图片。通过创建一个新的WebRequest对象,指定要下载的图片的URL地址。 2. 使用WebRequest的GetResponse方法发送请求,并获取服务器的响应。我们可以使用GetResponseStream方法来获取图片的二进制数据流。 3. 创建一个新的文件流对象,用于保存下载的图片。可以使用FileStream类来创建一个新的文件流对象,并指定图片的保存路径。 4. 从服务器响应的数据流读取二进制数据,并将其写入到本地文件流。我们可以使用StreamReader和StreamWriter类来读写数据。 5. 关闭文件流和网络响应,确保资源的正确释放。 6. 在Unity,可以使用Texture2D类来加载本地保存的图片。通过创建一个新的Texture2D对象,并使用它的LoadImage方法来加载本地图片。确保将本地图片的路径作为参数传递给LoadImage方法。 7. 最后,你可以将Texture2D对象应用到游戏对象的材质,或者使用它来作为UI组件的贴图。 这样,我们就可以在Unity从服务器下载图片并保存到本地,并通过Texture2D来加载和使用它们了。 ### 回答2: 在Unity下载服务器上的图片并保存到本地并加载的步骤如下: 1. 使用UnityWebRequest从服务器下载图片文件。首先,创建一个UnityWebRequest对象,并设置其下载的URL链接为服务器上的图片地址。然后,发送该请求并等待下载完成。 2. 在下载完成后,可以通过检查UnityWebRequest的isNetworkError和isHttpError属性来确保下载没有发生错误。如果没有错误,可以获取下载的图片数据。 3. 创建一个本地文件路径和文件名,在本地保存下载的图片。可以使用File.ReadAllBytes或File.WriteAllBytes方法将该图片数据保存到指定的本地路径和文件名。 4. 要在Unity场景加载保存的图片,可以使用Texture2D对象。创建一个新的Texture2D实例,并使用ImageConversion.LoadImage方法从本地路径加载已保存的图片。 5. 在需要显示图片的地方,比如材质的贴图,使用Texture2D对象作为贴图的属性值。 综上所述,以上是Unity下载服务器图片并保存到本地并加载的简要步骤。根据实际需求和具体情况,可以进行进一步的优化和扩展。 ### 回答3: 在Unity下载服务器上的图片并保存到本地并加载非常简单。以下是一个简单的步骤: 1. 首先,确保你有一个可以访问的图片的URL。你可以使用任何图像URL,也可以使用你自己的服务器上的图像URL。 2. 在Unity创建一个空的游戏对象,并添加一个脚本。 3. 在脚本使用WWW类下载图片。在Start函数添加以下代码: ``` IEnumerator DownloadImage() { string url = "https://example.com/image.jpg"; // 替换为你的图片URL WWW www = new WWW(url); yield return www; // 保存图像到本地 string savePath = Application.persistentDataPath + "/image.jpg"; System.IO.File.WriteAllBytes(savePath, www.bytes); } void Start() { StartCoroutine(DownloadImage()); } ``` 4. 这段代码使用WWW类创建了一个用于下载图片的请求。我们使用协程来处理异步下载,并在下载完成后保存图像到本地。 5. 图片下载完成后,我们使用Application.persistentDataPath(持久数据路径)保存图像。这个路径是应用程序可以使用的目录,可以用来保存应用程序的数据文件。 6. 现在,我们需要在Unity加载本地图像并将其显示出来。我们可以使用Sprite Renderer组件来显示加载的图像。在脚本继续添加以下代码: ``` void LoadImage() { string loadPath = Application.persistentDataPath + "/image.jpg"; // 从本地加载图像 Texture2D texture = new Texture2D(1, 1); texture.LoadImage(System.IO.File.ReadAllBytes(loadPath)); // 创建Sprite并显示图像 SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>(); spriteRenderer.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); } void Update() { if (Input.GetKeyDown(KeyCode.Space)) // 在Update函数检测键盘按键 { LoadImage(); } } ``` 7. 在这个代码,我们首先创建了一个空的2D纹理,并从本地文件加载图像数据。接下来,我们使用这个纹理创建了一个Sprite,并将其分配给SpriteRenderer组件来显示图像。 8. 最后,在Update函数,我们检测是否按下了空格键,并在按下时调用LoadImage函数来加载和显示图像。 这样,你就可以成功下载服务器图片保存到本地并加载Unity了。记得将图片URL替换为你自己服务器上的URL。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小温同学的账号

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

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

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

打赏作者

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

抵扣说明:

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

余额充值