编程语言
首页 > 编程语言> > Unity c#,截取屏幕截图并以jpg格式保存到文件中

Unity c#,截取屏幕截图并以jpg格式保存到文件中

作者:互联网

我正在尝试使用screencapture并将其保存为jpg格式的文件.我正在关注这个例子.

http://docs.unity3d.com/ScriptReference/Texture2D.EncodeToPNG.html

这是我到目前为止:

    string jpgFile = Application.persistentDataPath + "/scrn-1.jpg";
    Texture2D tex = new Texture2D (Screen.width, Screen.height);
    tex.ReadPixels (new Rect(0, 0, Screen.width, Screen.height), 0, 0);
    tex.Apply ();
    var bytes = tex.EncodeToJPG();
    Destroy (tex);
    System.IO.File.WriteAllBytes(jpgFile, bytes);

我发现在iOS上的Unity中运行它给了我:

JPEG参数struct mismatch:库认为大小是372,调用者期望360

但是,如果我将转换更改为tex.EncodeToPNG();并将文件名更改为.png一切正常.我不知道如何进行任何援助将不胜感激.谢谢.

解决方法:

我找到了this,可以将它保存为.jpg.我通常只使用capture screen并保存为.png.

干得好:

using UnityEngine;
using System.Collections;

public class HiResScreenShots : MonoBehaviour {
    public int resWidth = 2550; 
    public int resHeight = 3300;

    private bool takeHiResShot = false;

    public static string ScreenShotName(int width, int height) {
        return string.Format("{0}/screenshots/screen_{1}x{2}_{3}.png", 
                             Application.dataPath, 
                             width, height, 
                             System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
    }

    public void TakeHiResShot() {
        takeHiResShot = true;
    }

    void LateUpdate() {
        takeHiResShot |= Input.GetKeyDown("k");
        if (takeHiResShot) {
            RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
            camera.targetTexture = rt;
            Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
            camera.Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
            camera.targetTexture = null;
            RenderTexture.active = null; // JC: added to avoid errors
            Destroy(rt);
            byte[] bytes = screenShot.EncodeToPNG();
            string filename = ScreenShotName(resWidth, resHeight);
            System.IO.File.WriteAllBytes(filename, bytes);
            Debug.Log(string.Format("Took screenshot to: {0}", filename));
            takeHiResShot = false;
        }
    }
}

如果您只是想要任何类型的图片我强烈推荐这个:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour 
{
    void onm ouseDown() 
    {
        Application.CaptureScreenshot("Screenshot.png");
    }
}

简单有效.

标签:c,android,ios,unity3d,texture2d
来源: https://codeday.me/bug/20190528/1172624.html