More in this category:
Posted on June 16, 2014, by Richard Knol
Making a screenshot in Unity is easy. Just call Application.CaptureScreenshot() and it saves a PNG file for you. But what if you want to use the screenshot in your game or if you want to upload it to a server. You could read the saved file back in, but is a crappy solution.public static Texture2D TakeScreenshot(int width, int height,
Camera screenshotCamera) {
if(width<=0 || height<=0) return null;
if(screenshotCamera == null) screenshotCamera = Camera.main;
Texture2D screenshot = new Texture2D(width, height, TextureFormat.RGB24, false);
RenderTexture renderTex = new RenderTexture(width, height, 24);
screenshotCamera.targetTexture = renderTex;
screenshotCamera.Render();
RenderTexture.active = renderTex;
screenshot.ReadPixels(new Rect(0, 0, width, height), 0, 0);
screenshot.Apply(false);
screenshotCamera.targetTexture = null;
RenderTexture.active = null;
Destroy(renderTex);
return screenshot;
}
public static Texture2D TakeScreenshot(int width, int height,
Camera screenshotCamera, string saveToFileName) {
Texture2D screenshot = TakeScreenshot(width, height, screenshotCamera);
if(screenshot != null && saveToFileName!=null) {
if(Application.platform==RuntimePlatform.OSXPlayer ||
Application.platform==RuntimePlatform.WindowsPlayer &&
Application.platform!=RuntimePlatform.LinuxPlayer
|| Application.isEditor) {
byte[] bytes;
if(saveToFileName.ToLower().EndsWith(".jpg"))
bytes = screenshot.EncodeToJPG();
else bytes = screenshot.EncodeToPNG();
FileStream fs = new FileStream(saveToFileName, FileMode.OpenOrCreate);
BinaryWriter w = new BinaryWriter(fs);
w.Write(bytes);
w.Close();
fs.Close();
}
}
return screenshot;
}
public static void AddScreenshotToForm(int width, int height,
Camera screenshotCamera, WWWForm uploadForm, string fieldName, string extension) {
Texture2D screenshot = TakeScreenshot(width, height, screenshotCamera);
if(screenshot != null && fieldName!=null && uploadForm!=null) {
byte[] bytes;
string mimeType;
if(extension.ToLower()==("jpg")) {
bytes = screenshot.EncodeToJPG();
mimeType = "image/jpeg";
} else {
bytes = screenshot.EncodeToPNG();
mimeType = "image/png";
}
uploadForm.AddBinaryData(fieldName, bytes, fieldName+"."+extension, mimeType);
}
}