Take a screenshot of the specified camera in Unity and convert the picture to Base64

Problem background:

The requirement is to only cut the scene, not include the UI, and save the screenshot in Base64 format to the Web display.

Program:

Specify the camera screenshot:

 1 /// <summary>
 2         /// 指定相机截屏
 3         /// </summary>
 4         /// <param name="camera"></param>
 5         /// <param name="rect"></param>
 6         /// <returns></returns>
 7         public byte[] CaptureScreen(Camera camera, Rect rect)
 8         {
 9             RenderTexture rt = new RenderTexture(camera.pixelWidth, camera.pixelHeight, 0);
10 
11             camera.targetTexture = rt;
12             camera.Render();
13 
14             RenderTexture.active = rt;
15             Texture2D screenShot = new Texture2D(camera.pixelWidth, camera.pixelHeight, TextureFormat.RGBA32, false);
16 
17             screenShot.ReadPixels(rect, 0, 0);
18             screenShot.Apply();
19 
20             camera.targetTexture = null;
21             RenderTexture.active = null;
22             GameObject.Destroy(rt);
23 
24             byte[] bytes = screenShot.EncodeToPNG();
25 
26             return bytes;
27         }

I didn't write to the memory here, because I don't need it, I uploaded it directly.

Transfer to Base64 is very simple:

 1  /// <summary>
 2         /// 图片流转Base64
 3         /// </summary>
 4         /// <param name="bytesArr"></param>
 5         /// <returns></returns>
 6         public String Texture2DToBase64(byte[] bytesArr)
 7         {
 8             string strbaser64 = Convert.ToBase64String(bytesArr);
 9 
10             return strbaser64;
11         }

Base64:

One of the most common encoding methods used to transmit 8Bit byte code on the network , Base64 encoding is a process from binary to character, which can be used to transfer longer identification information in the HTTP environment. Base64 encoding is unreadable, and can only be read after decoding. Base64 is widely used in various fields of computers due to the above advantages, (Encyclopedia)

 

Screenshot example:

 

Guess you like

Origin www.cnblogs.com/answer-yj/p/12675192.html