保存Texture2D到文件不能正常工作

本文关键字:工作 常工作 Texture2D 文件 不能 保存 | 更新日期: 2023-09-27 18:05:01

所以我基于Texture2D创建了这个类。EncodeToPNG代码示例在Unity的网站。当我执行它时,我没有得到任何错误,但我也没有看到一个新文件被创建。我哪里做错了?

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)
        {
        }
    } 
}

保存Texture2D到文件不能正常工作

您没有启动协程,您需要在GrabJPG中调用StartCodoutine:

StartCoroutine(SaveJPG());
https://docs.unity3d.com/Manual/Coroutines.html

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

p。顺便说一下,你可以使用Application。CaptureScreenshot