Search code examples
c#unity-game-enginetexture2d

Loading an image as Texture2D


In my program, I want to save some screenshots and load them later on to compute somethings. I created a methode to compute the image names:

static public string generatePhotoName (string cameraName, float time)
{
    return "G:/Data/unity/cameraDemo/" + 
        DataController.measurmentPath + 
        "/photos" + "/" + 
        cameraName + "/" + 
        time.ToString () + "_" + cameraName + ".png";
}

This worked fine for saving, but when I try to load an image, File.Exists (filePath)returns false.

But when I hardcoded the filepath, loading works fine too:

static public string generatePhotoName (string cameraName, float time)
{
    return "G:/Data/unity/cameraDemo/demo/photos/Camera/test.png";
}

It even works with "real" image names(i.e. 3.827817_Camera.png).

Using Path.Combine(...) and changing "/" to "\" did not change anything...

// edit: this is my load methode

static public Texture2D loadPhotoToTexture (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.
    } else {
        Debug.Log (filePath + " does not exist");
    }
    return tex;
}`

// edit2: some more code

This is how I call the methode Texture2D photo = DataController.loadPhotoToTexture(photoData.getFileName ());

And this is my class PhotoData

public class PhotoData : BaseData
{
    private string _cameraName;

    public string cameraName {
    get { return _cameraName; }
    set { _cameraName = value; }
    }

    private float _time;

    public float time {
        get { return _time; }
        set { _time = value; }
    }

    public PhotoData ()
    {
    }

    public PhotoData (string cameraName, float time)
    {
        _cameraName = cameraName;
        _time = time;
    }

    public string getFileName ()
    {
        return PlayerController.generatePhotoName (_cameraName, _time);
    }
}

Solution

  • The problem was, that I tried to save and load the screenshots in one Update()-call.

    I fixed it by changing it to right-click to take and save a screenshot and left-click to load the screenshot.