> 将UNITY3D RenderTexture动态渲染出来的图保存到本地
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

using UnityEngine;
using System.Collections;
using System.IO;

public class CreateImage : MonoBehaviour
{
public RenderTexture render_texture;
public Texture2D texture2D;
public Plane plane;

public Camera _cameraWithRendTexture;
public TextMesh _percentMesh;
public TextMesh _nameMesh;
public int _heightInPixelsOfCertificate = 1488;

public void SaveCertificate()
{
if (!_cameraWithRendTexture)
_cameraWithRendTexture = GameObject.Find("CertificateCamera").GetComponent<Camera>();
if (!_nameMesh)
_nameMesh = GameObject.Find("bName").GetComponent<TextMesh>();
if (!_percentMesh)
_percentMesh = GameObject.Find("dPercent").GetComponent<TextMesh>();
RenderTexture.active = _cameraWithRendTexture.targetTexture;
Texture2D newTexture = new Texture2D(_cameraWithRendTexture.targetTexture.width, _cameraWithRendTexture.targetTexture.height, TextureFormat.ARGB32, false);
newTexture.ReadPixels(new Rect(0, 0, _cameraWithRendTexture.targetTexture.width, _cameraWithRendTexture.targetTexture.height), 0, 0, false);
newTexture.Apply();
Color[] colorArrayCropped = newTexture.GetPixels(0, newTexture.height - _heightInPixelsOfCertificate, newTexture.width, _heightInPixelsOfCertificate);
Texture2D croppedTex = new Texture2D(newTexture.width, _heightInPixelsOfCertificate, TextureFormat.ARGB32, false);
croppedTex.SetPixels(colorArrayCropped);
croppedTex = FillInClear(croppedTex, _cameraWithRendTexture.backgroundColor);
croppedTex.Apply();
byte[] bytes = croppedTex.EncodeToPNG();

File.WriteAllBytes("Save File Path Here", bytes);
}

public Texture2D FillInClear(Texture2D tex2D, Color whatToFillWith)
{

for (int i = 0; i < tex2D.width; i++)
{
for (int j = 0; j < tex2D.height; j++)
{
if (tex2D.GetPixel(i, j) == Color.clear)
tex2D.SetPixel(i, j, whatToFillWith);
}
}
return tex2D;
}

}