public Camera AC;
int capx = 0;
int capy = 0;
int capwidth = 1920;
int capheight = 1080;
IEnumerator getScreenTexture()
{
yield return new WaitForEndOfFrame();
bytes = CameraCapture(AC).EncodeToJPG();
Sprite sprite = Sprite.Create(CameraCapture(AC), new Rect(0, 0, CameraCapture(AC).width, CameraCapture(AC).height), new Vector2(0.5f, 0.5f));
_IMG.GetComponent<UnityEngine.UI.Image>().sprite = sprite;
bytes2= ReSetTextureSize(BytesToTexture2D(bytes, 1920, 1080), 960, 540).EncodeToJPG();
File.WriteAllBytes(Application.dataPath + Time.time + ".jpg", bytes2);
}
public static Texture2D ReSetTextureSize(Texture2D tex, int width, int height)
{
var rendTex = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
rendTex.Create();
UnityEngine.Graphics.SetRenderTarget(rendTex);
GL.PushMatrix();
GL.Clear(true, true, UnityEngine.Color.clear);
GL.PopMatrix();
var mat = new Material(Shader.Find("Unlit/Transparent"));
mat.mainTexture = tex;
UnityEngine.Graphics.SetRenderTarget(rendTex);
GL.PushMatrix();
GL.LoadOrtho();
mat.SetPass(0);
GL.Begin(GL.QUADS);
GL.TexCoord2(0, 0);
GL.Vertex3(0, 0, 0);
GL.TexCoord2(0, 1);
GL.Vertex3(0, 1, 0);
GL.TexCoord2(1, 1);
GL.Vertex3(1, 1, 0);
GL.TexCoord2(1, 0);
GL.Vertex3(1, 0, 0);
GL.End();
GL.PopMatrix();
var finalTex = new Texture2D(rendTex.width, rendTex.height, TextureFormat.ARGB32, false);
RenderTexture.active = rendTex;
finalTex.ReadPixels(new Rect(0, 0, finalTex.width, finalTex.height), 0, 0);
finalTex.Apply();
return finalTex;
}
public static Texture2D BytesToTexture2D(byte[] bytes, int w, int h)
{
Texture2D texture2D = new Texture2D(w, h);
texture2D.LoadImage(bytes);
return texture2D;
}
public Texture2D CameraCapture(Camera camera)
{
RenderTexture render = new RenderTexture(capwidth, capheight, -1);//创建一个RenderTexture对象
camera.gameObject.SetActive(true);//启用截图相机
camera.targetTexture = render;//设置截图相机的targetTexture为render
camera.Render();//手动开启截图相机的渲染
RenderTexture.active = render;//激活RenderTexture
Texture2D tex = new Texture2D(capwidth, capheight, TextureFormat.ARGB32, false);//新建一个Texture2D对象
tex.ReadPixels(new Rect(capx, capy, capwidth, capheight), 0, 0, false);//按照设定区域读取像素;注意是以左下角为原点读取
tex.Apply();//保存像素信息
camera.targetTexture = null;//重置截图相机的targetTexture
RenderTexture.active = null;//关闭RenderTexture的激活状态
Destroy(render);//删除RenderTexture对象
#if UNITY_EDITOR
UnityEditor.AssetDatabase.Refresh();//刷新Unity的资产目录
#endif
return tex;//返回Texture2D对象,方便游戏内展示和使用
}