存储屏幕截图并将其从基于浏览器的应用程序上传到网络服务器

存储屏幕截图并将其从基于浏览器的应用程序上传到网络服务器

问题描述:

因此,我只是想快速入门,了解如何从基于浏览器的应用程序上传屏幕截图到网络服务器。由于我无法在本地保存文件然后上传,我是否需要将其存储在纹理变量中?我对这个基础知识有点困惑,但我只想指出正确的方向。我使用字符串变量在本地研究了在线地址的所有内容,但这对于基于浏览器的应用程序无效,对吗?只是寻找一些关于如何开始为此建立POC的指导。谢谢您的帮助。存储屏幕截图并将其从基于浏览器的应用程序上传到网络服务器

我所知道的: 我可以采取的截图(但现在我只知道如何将它保存到本地) 我可以上传一个文件(但只能从本地路径)

大问题: 我如何才能将屏幕截图保存在内存中?不知道这是否是一个正确的问题,但我希望有人知道我在想什么。

最终我想要做的就是截图,然后直接保存到MySQL服务器。

Texture2D.EncodeToPNG的Unity帮助页面有一个捕获和上传屏幕截图的完整示例。

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

// Saves screenshot as PNG file. 
using UnityEngine; 
using System.Collections; 
using System.IO; 

public class PNGUploader : MonoBehaviour { 
    // Take a shot immediately 
    IEnumerator Start() { 
     yield return UploadPNG(); 
    } 

    IEnumerator UploadPNG() { 
     // We should only read the screen buffer after rendering is complete 
     yield return new WaitForEndOfFrame(); 

     // Create a texture the size of the screen, RGB24 format 
     int width = Screen.width; 
     int height = Screen.height; 
     Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false); 

     // Read screen contents into the texture 
     tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); 
     tex.Apply(); 

     // Encode texture into PNG 
     byte[] bytes = tex.EncodeToPNG(); 
     Object.Destroy(tex); 

     // For testing purposes, also write to a file in the project folder 
     // File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes); 


     // Create a Web Form 
     WWWForm form = new WWWForm(); 
     form.AddField("frameCount", Time.frameCount.ToString()); 
     form.AddBinaryData("fileUpload",bytes); 

     // Upload to a cgi script 
     WWW w = new WWW("http://localhost/cgi-bin/env.cgi?post", form); 
     yield return w; 

     if (w.error != null) { 
      Debug.Log(w.error); 
     } else { 
      Debug.Log("Finished Uploading Screenshot"); 
     } 
    } 

} 
+0

好,冬暖夏凉。我将该代码放入新的cs文件并将其附加到保存按钮。我在脚本的顶部看到'IEnumerator Start()'。这是否意味着它应该在应用程序启动后立即运行?在事情成功或失败的时刻,我没有在控制台中得到任何反馈。我需要做什么来执行这个脚本? – greyBow

+0

是的,启动意味着它在启动时立即运行。要附加到一个按钮,您需要删除启动功能,并将以下内容替换为: 'void TakeScreenshot(){ StartCoroutine(“UploadPNG”); }' 之后,将按钮的OnClick处理程序附加到检查器中的TakeScreenshot。当然,您仍然需要将您的特定上传逻辑编码到您自己的URL,因为它当前正在将数据发送到示例URL。 –