Unity renders the current scene to the picture and exports the picture (local/server)

 
 

In Unity, the scene can be rendered as an image using the following code:

// 创建一个RenderTexture作为渲染目标
 RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 24);
// 设置相机的渲染目标为该
RenderTexture Camera.main.targetTexture = rt; 
// 渲染相机所在的场景 
Camera.main.Render(); 
// 恢复相机的渲染目标为默认值 
Camera.main.targetTexture = null;
// 将RenderTexture转换为Texture2D Texture2D 
screenshot = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false); RenderTexture.active = rt;
screenshot.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); 
screenshot.Apply();
 RenderTexture.active = null; 
// 保存截图为PNG格式的文件
 byte[] bytes = screenshot.EncodeToPNG(); 
File.WriteAllBytes(Application.dataPath + "/screenshot.png", bytes);

This code creates a RenderTexture, sets the camera's rendering target to the RenderTexture, renders the scene where the camera is located, converts the RenderTexture to a Texture2D, and finally saves the Texture2D as a file in PNG format.

In Unity, images can be uploaded to a web server using the WWW class. Here is sample code:

 
 
IEnumerator UploadImage()
{ 
     // 加载本地图片 
     string imagePath = Application.dataPath + "/image.png"; byte[] imageData =     File.ReadAllBytes(imagePath); 
     // 创建FormData对象,并添加需要上传的数据
     WWWForm form = new WWWForm();
     form.AddField("name", "image");
     form.AddBinaryData("file", imageData, "image.png", "image/png");
     // 创建一个HTTP请求,并发送FormData数据 
     using (UnityWebRequest request = UnityWebRequest.Post("http://example.com/upload.php", form)) 
        { 
            yield return request.SendWebRequest(); 
            if (request.result != UnityWebRequest.Result.Success) 
            { 
                Debug.LogError(request.error); 
            } 
            else
            { 
                Debug.Log("Upload complete!");
            }
        }
 }

This code first loads the local image, then creates a FormData object, and adds the data to be uploaded to it. Then create an HTTP request and send FormData data. Finally, log information is output according to the request result. In actual application, you need to replace " http://example.com/upload.php " with the actual web server address.

Guess you like

Origin blog.csdn.net/qq_66312646/article/details/130063683