- Home /
Load Image in Unity using path from user
huy Guys I am here to know how to load an image from any place of my hard disk(depend on user) in unity application when my application is running. a well known example is open(Cntrl + O) in any application. just same as. I am using this code but gave me error "could not load file at bla bla bla path" My code is
using UnityEngine;
using System.Collections;
using System.IO;
public class image_loading : MonoBehaviour {
private string url = @"file://C:/Users/Muhammad/Downloads/test.jpg";//suppose this path somewhere in my PC
// Use this for initialization
void Start() {
StartCoroutine(LoadImage());
}
IEnumerator LoadImage() {
Texture2D new_Texture = new Texture2D(960, 720, TextureFormat.DXT1, false);
WWW www = new WWW(url);
yield return www;
www.LoadImageIntoTexture(new_Texture);
this.GetComponent<Renderer>().material.mainTexture = new_Texture;
}
// Update is called once per frame
void Update () {
}
}
Answer by rjgilmour · Jan 29, 2019 at 03:33 PM
This worked for me using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO;
public class LoadImage : MonoBehaviour
{
public string imagePath;
public void Start()
{
}
public void AssignTexture()
{
GameObject.FindWithTag("Floor").GetComponent<MeshRenderer>().material.mainTexture = LoadPNG(imagePath);
}
public static Texture2D LoadPNG(string filePath)
{
Texture2D tex = null;
byte[] fileData;
if (File.Exists(filePath))
{
fileData = File.ReadAllBytes(filePath);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
}
return tex;
}
}
Attach this script to an Empty called LoadImage, then link the Empty LoadImage to the button and use the function called AssignTexture().
I want to be able to prompt the user to browse their files however and haven't found a solution yet. Asking users to copy and paste a filepath is a bit clumsy.
Your answer
![](https://koobas.hobune.stream/wayback/20220612042014im_/https://answers.unity.com/themes/thub/images/avi.jpg)