【问题标题】:Saving Texture2D to file not working properly将 Texture2D 保存到文件无法正常工作
【发布时间】:2015-07-27 15:16:07
【问题描述】:

所以我根据 Unity 网站上的 Texture2D.EncodeToPNG 代码示例创建了这个类。执行它时我没有收到任何错误,但我也没有看到创建的新文件。我在这里做错了什么?

public class CreateJPG : MonoBehaviour
{   
    public int width = 1050;
    public int height = 700;

    string fileName;
    string filePath;
    // Texture2D tex;

    public void GrabJPG () {
        SaveJPG();
        Debug.Log("GrabJPG Executing");
    }

    IEnumerator SaveJPG()
    {   
        // We should only read the screen buffer after rendering is complete
        yield return new WaitForEndOfFrame();

        // Create a texture the size of the screen, RGB24 format
        Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
        tex.ReadPixels(new Rect(0,0,width,height),0,0);
        tex.Apply();

        // Encode texture into JPG
        byte[] bytes = tex.EncodeToJPG(60);
        Object.Destroy(tex);

        // Get filePrefix from GameSetup array index
        GameObject init = GameObject.FindGameObjectWithTag("Initializer");
        GameSetup gameSetup = init.GetComponent<GameSetup>();
        string prefix = gameSetup.filePrefix;
        string subDir = gameSetup.subDir;

        string dtString = System.DateTime.Now.ToString("MM-dd-yyyy_HHmmssfff");
        fileName = prefix+dtString+".jpg";
        filePath = "/Users/kenmarold/Screenshots/"+subDir+"/";

        Debug.Log("SaveJPG Executing");

        File.WriteAllBytes(filePath+fileName, bytes);
        Debug.Log("Your file was saved at " + filePath+subDir+prefix+fileName);

        if(width > 0 && height > 0)
        {

        }
    } 
}

【问题讨论】:

  • 目录存在吗?有什么例外吗?
  • 它确实存在,不,我没有遇到任何异常。很奇怪,我只是没看出有什么问题。
  • 尝试将您的代码从纹理创建到最后的Debug.Log放入try-catch中,在控制台中打印您的异常消息+跟踪。

标签: c# unity3d io textures


【解决方案1】:

你没有启动你的协程,你需要在 GrabJPG 中调用StartCodoutine

StartCoroutine(SaveJPG());

https://docs.unity3d.com/Manual/Coroutines.html

https://unity3d.com/learn/tutorials/modules/intermediate/scripting/coroutines

P。 S.对了,你可以用Application.CaptureScreenshot

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 2021-08-04
    • 2023-03-28
    相关资源
    最近更新 更多