public override void OnInspectorGUI() { if (GUILayout.Button("Generate Thumb")) { Camera cam = (Camera)target; CameraClearFlags clearFlags = cam.clearFlags; cam.clearFlags = CameraClearFlags.Depth; RenderTexture renTex = new RenderTexture(size, size, 1); cam.targetTexture = renTex; cam.Render(); cam.targetTexture = null; Texture2D tex = new Texture2D(size, size); RenderTexture.active = renTex; tex.ReadPixels(new Rect(0, 0, size, size), 0, 0); RenderTexture.active = null; byte[] data = tex.EncodeToPNG(); string scenePath = Path.GetFullPath(Path.GetDirectoryName(EditorSceneManager.GetActiveScene().path)); string sceneName = EditorSceneManager.GetActiveScene().name; string file = scenePath + "/Thumbnails/" + sceneName + ".png"; File.WriteAllBytes(file, data); Debug.Log("Thumbnail saved to: " + file); cam.clearFlags = clearFlags; } base.OnInspectorGUI(); }
void OnPostRender() { if(!mat) { mat = new Material( "Shader \"Hidden/SetAlpha\" {" + "SubShader {" + " Pass {" + " ZTest Always Cull Off ZWrite Off" + " ColorMask A" + " Color (1,1,1,1)" + " }" + "}" + "}" ); } // Draw a quad over the whole screen with the above shader GL.PushMatrix (); GL.LoadOrtho (); for (var i = 0; i < mat.passCount; ++i) { mat.SetPass (i); GL.Begin( GL.QUADS ); GL.Vertex3( 0, 0, 0.1f ); GL.Vertex3( 1, 0, 0.1f ); GL.Vertex3( 1, 1, 0.1f ); GL.Vertex3( 0, 1, 0.1f ); GL.End(); } GL.PopMatrix (); DestroyImmediate(tex); tex = new Texture2D(Mathf.FloorToInt(GetComponent<Camera>().pixelWidth), Mathf.FloorToInt(GetComponent<Camera>().pixelHeight)); tex.filterMode = filterMode; tex.ReadPixels(new Rect(0, 0, GetComponent<Camera>().pixelWidth, GetComponent<Camera>().pixelHeight), 0, 0); tex.Apply(); }
public static Texture2D Screenshot(Rect rect) { Camera camera = Camera.main; //Camera camera = //create temp textures, one for the camera to render RenderTexture renderTexture = new RenderTexture((int)rect.width, (int)rect.height, 16, RenderTextureFormat.ARGB32); //and one for the file Texture2D texture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false); //Texture2D texture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false); //set renderTexture RenderTexture.active = renderTexture; RenderTexture oldTexture = Camera.main.targetTexture; camera.targetTexture = renderTexture; camera.Render(); //read the content of the camera into the texture texture.ReadPixels(rect, 0, 0); //texture.Apply(); //release the renders RenderTexture.active = null; //camera.targetTexture = null; camera.targetTexture = oldTexture; return texture; }
IEnumerator ScreenshotEncode() { // wait for graphics to render yield return new WaitForEndOfFrame(); // create a texture to pass to encoding Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); // put buffer into texture texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); texture.Apply(); // split the process up--ReadPixels() and the GetPixels() call inside of the encoder are both pretty heavy yield return 0; byte[] bytes = texture.EncodeToPNG(); count = PlayerPrefs.GetInt("count"); // save our test image (could also upload to WWW) File.WriteAllBytes(Application.dataPath + "/../testscreen-" + count + ".png", bytes); count++; PlayerPrefs.SetInt("count", count); // Added by Karl. - Tell unity to delete the texture, by default it seems to keep hold of it and memory crashes will occur after too many screenshots. DestroyObject(texture); Debug.Log( Application.dataPath + "/../testscreen-" + count + ".png" ); }
public IEnumerator TakePicture() { foreach (var ren in GetComponentsInChildren<MeshRenderer>()) { ren.enabled = false; } Camera.main.fieldOfView = 54; RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 24); Camera.main.targetTexture = rt; Texture2D screenShot = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); Camera.main.Render(); RenderTexture.active = rt; screenShot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); screenShot.Apply(); Camera.main.targetTexture = null; RenderTexture.active = null; Camera.main.fieldOfView = 72; Fader.FadeIn(0.2f); yield return new WaitForSeconds(0.2f); Fader.FadeOut(0.4f); iPhoneTweener._.SlideIn(screenShot, Random.Range(1, 150), Random.Range(2, 15)); foreach (var ren in GetComponentsInChildren<MeshRenderer>()) { ren.enabled = true; } ; }
/// <summary> /// 对相机截图。 /// </summary> /// <returns>The screenshot2.</returns> /// <param name="camera">Camera.要被截屏的相机</param> /// <param name="rect">Rect.截屏的区域</param> public static Texture2D CaptureCamera(string _fileParentPath, string _fileName) { // 创建一个RenderTexture对象 RenderTexture rt = new RenderTexture((int)Screen.width, (int)Screen.height, 24); // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机 Camera.main.targetTexture = rt; Camera.main.Render(); //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。 //ps: camera2.targetTexture = rt; //ps: camera2.Render(); //ps: ------------------------------------------------------------------- // 激活这个rt, 并从中中读取像素。 RenderTexture.active = rt; screenShot = new Texture2D((int)Screen.width * 3 / 4, (int)Screen.height, TextureFormat.RGB24, false); screenShot.ReadPixels(new Rect(Screen.width * 1 / 8, 0, Screen.width * 3 / 4, Screen.height), 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素 screenShot.Apply(); // 重置相关参数,以使用camera继续在屏幕上显示 Camera.main.targetTexture = null; //ps: camera2.targetTexture = null; RenderTexture.active = null; // JC: added to avoid errors GameObject.Destroy(rt); // 最后将这些纹理数据,成一个png图片文件 //byte[] bytes = screenShot.EncodeToPNG(); byte[] bytes = screenShot.EncodeToJPG(); string filename = _fileParentPath + _fileName; System.IO.File.WriteAllBytes(filename, bytes); return screenShot; }
void LateUpdate() { if (Input.GetKeyUp(KeyCode.S)) { #if !UNITY_WEBPLAYER int resWidth = 4096, resHeight = 2048; RenderTexture rt = new RenderTexture(resWidth, resHeight, 24); camera.targetTexture = rt; camera.Render(); RenderTexture prevActive = RenderTexture.active; RenderTexture.active = rt; Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.ARGB32, false); screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0, false); camera.targetTexture = null; RenderTexture.active = prevActive; Destroy(rt); screenShot = DownSample(screenShot); byte[] bytes = screenShot.EncodeToPNG(); string filename = ScreenshotPath(); System.IO.File.WriteAllBytes(filename, bytes); Debug.Log("Screenshot stored at: '" + filename + "'"); #else Debug.LogWarning("Screen shot not supported in WebPlayer."); #endif } }
static int ReadPixels(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 4) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D)); UnityEngine.Rect arg0 = StackTraits<UnityEngine.Rect>.Check(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); int arg2 = (int)LuaDLL.luaL_checknumber(L, 4); obj.ReadPixels(arg0, arg1, arg2); return 0; } else if (count == 5) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D)); UnityEngine.Rect arg0 = StackTraits<UnityEngine.Rect>.Check(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); int arg2 = (int)LuaDLL.luaL_checknumber(L, 4); bool arg3 = LuaDLL.luaL_checkboolean(L, 5); obj.ReadPixels(arg0, arg1, arg2, arg3); return 0; } else { return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Texture2D.ReadPixels"); } } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } }
IEnumerator ApplyShare() { shareToFBPanel_anim.SetBool ("show", false); string message = transform.parent.Find ("Message").Find ("Text").GetComponent<Text> ().text; yield return new WaitForSeconds(.5f); #if UNITY_EDITOR Debug.Log ("Capture screenshot and share."); Debug.Log ("Message: "+message); GameObject.Find ("ResultPanel").SendMessage("ShareToFB", false); #elif UNITY_ANDROID var snap = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); snap.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); snap.Apply(); var screenshot = snap.EncodeToPNG(); var wwwForm = new WWWForm(); wwwForm.AddBinaryData("image", screenshot, "screenshot.png"); wwwForm.AddField("message", message); FB.API( "/me/photos", Facebook.HttpMethod.POST, delegate (FBResult r) { GameObject.Find("ResultPanel").SendMessage("ShareToFB", false); }, wwwForm ); #endif }
// return file name public IEnumerator TakeScreenShot() { yield return new WaitForEndOfFrame(); Camera camOV = OVcamera.GetComponent<Camera>(); RenderTexture currentRT = RenderTexture.active; RenderTexture.active = camOV.targetTexture; camOV.Render(); Texture2D imageOverview = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false); imageOverview.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0); imageOverview.Apply(); RenderTexture.active = currentRT; // Encode texture into PNG byte[] bytes = imageOverview.EncodeToPNG(); // save in memory path = Application.persistentDataPath + "/Screenshot.png"; Debug.Log (path); System.IO.File.WriteAllBytes(path, bytes); }
public void RenderCamera(int resWidth, int resHeight, string path){ // Set Camera Camera.main.orthographic = true; Camera.main.orthographicSize = MapSize * 0.05f; Pivot.localPosition = new Vector3(MapSize * 0.05f, 0, -MapSize * 0.05f); Pivot.rotation = Quaternion.identity; // Take Screenshoot RenderTexture rt = new RenderTexture(resWidth, resHeight, 24); Camera.main.targetTexture = rt; Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); Camera.main.Render(); RenderTexture.active = rt; screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0); Camera.main.targetTexture = null; RenderTexture.active = null; // JC: added to avoid errors Destroy(rt); byte[] bytes; if(path.Contains(".png")) bytes = screenShot.EncodeToPNG(); else bytes = screenShot.EncodeToJPG(); System.IO.File.WriteAllBytes(path, bytes); // Restart Camera Camera.main.orthographic = false; RestartCam(); }
/* ---------------------------------------- * A coroutine where the screenshot is taken according to the preferences * set by the user */ IEnumerator ReadPixels() { // bytes array for converting pixels to image format byte[] bytes; // Wait for the end of the frame, so GUI elements are included in the screenshot yield return new WaitForEndOfFrame(); // Create new Texture2D variable of the same size as the image capture area texture = new Texture2D (sw,sh,TextureFormat.RGB24,false); // Read Pixels from the capture area texture.ReadPixels(sRect,0,0); // Apply pixels read com capture area into 'texture' texture.Apply(); // IF selected method is 'ReadPixelsJpg'... if (captMethod == method.ReadPixelsJpg){ // store as bytes the texture encoded to JPG (using 'jpgQuality' as quality settings) bytes = texture.EncodeToJPG(jpgQuality); WriteBytesToFile(bytes, ".jpg"); } else if (captMethod == method.ReadPixelsPng){ // store as bytes the texture encoded to PNG bytes = texture.EncodeToPNG(); WriteBytesToFile(bytes, ".png"); } }
IEnumerator ScreenshotEncode() { // wait for graphics to render yield return new WaitForEndOfFrame(); // create a texture to pass to encoding Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); // put buffer into texture texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); texture.Apply(); // split the process up--ReadPixels() and the GetPixels() call inside of the encoder are both pretty heavy yield return 0; byte[] bytes = texture.EncodeToPNG(); // save our test image (could also upload to WWW) string filePath = Application.dataPath + "/screenshots/" + KSMetric.List[GraphAxis.me.xLabel].Name + "_" + KSMetric.List[GraphAxis.me.yLabel].Name + "/" + GraphAxis.me.legendTitles[GraphAxis.me.selectedLegend] + ".png"; FileInfo file = new System.IO.FileInfo(filePath); file.Directory.Create(); // If the directory already exists, this method does nothing. File.WriteAllBytes(file.FullName, bytes); //File.WriteAllBytes(filePath, bytes); //File.WriteAllBytes(Application.dataPath + "/../testscreen-" + count + ".png", bytes); count++; // Added by Karl. - Tell unity to delete the texture, by default it seems to keep hold of it and memory crashes will occur after too many screenshots. DestroyObject( texture ); //Debug.Log( Application.dataPath + "/../testscreen-" + count + ".png" ); }
public Texture2D GetIconOf(Transform prefab) { // Spawn us a prefab to look at and set it's layer to the iconLayer so // other cameras can't see it. Transform tempPrefab = (Transform)Instantiate(prefab, transform.position, Quaternion.identity); tempPrefab.gameObject.layer = iconLayer; // Force the camera to render because this can be called many times a frame. snapshotCam.Render(); // Set the active render target of the game to be ours. RenderTexture.active = snapshotCam.targetTexture; // Convert the render texture to a normal usable texture. Texture2D newIcon = new Texture2D(snapshotCam.targetTexture.width, snapshotCam.targetTexture.height, TextureFormat.ARGB32, false, true); newIcon.ReadPixels(new Rect(0, 0, newIcon.width, newIcon.height), 0, 0, false); newIcon.Apply(); // Set the active render texture to null (this might no be needed). RenderTexture.active = null; // disable the renderer of the spawned prefab because just removing it is // not enough. tempPrefab.GetComponent<MeshRenderer>().enabled = false; // remove the spawned prefab. Destroy(tempPrefab.gameObject); // And finally return the new icon texture return newIcon; }
IEnumerator UploadJPG() { // We should only read the screen after all 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; var 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(); Destroy( tex ); // Create a Web Form WWWForm form = new WWWForm(); form.AddField("frameCount", Time.frameCount.ToString()); form.AddBinaryData("fileUpload", bytes, @"C:\images\img_file.jpg", "image/jpg"); // Upload to a cgi script WWW w = new WWW(url, form); yield return w; if (!string.IsNullOrEmpty(w.error)) { print(w.error); } else { print("Finished Uploading Screenshot"); } }
// Based on: http://wiki.unity3d.com/index.php?title=TakeScreenshot // ****** Notice : It doesn't works in Web Player environment. ****** // ****** It works in PC environment. ****** // Default method have some problem, when you take a Screen shot for your game. // So add this script. // CF Page : http://technology.blurst.com/unity-jpg-encoding-javascript/ // made by Jerry ( [email protected] ) IEnumerator TakeScreenshot() { // wait for graphics to render yield return new WaitForEndOfFrame(); // we do nothing on web player, since we can't write files #if !UNITY_WEBPLAYER // create a texture to pass to encoding Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); // put buffer into texture texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); texture.Apply(); // split the process up--ReadPixels() and the GetPixels() call inside of the encoder are both pretty heavy yield return 0; byte[] bytes = texture.EncodeToPNG(); // save our test image (could also upload to WWW) string fn = Path.Combine(Application.persistentDataPath, "screenshot-" + count + ".png"); File.WriteAllBytes(fn, bytes); Debug.Log ("Wrote screenshot to:" + fn); count++; // Added by Karl. - Tell unity to delete the texture, by default it seems to keep hold of it and memory crashes will occur after too many screenshots. DestroyObject( texture ); //Debug.Log( Application.dataPath + "/../testscreen-" + count + ".png" ); #endif }
public static UnityEngine.Texture2D CreateTemporaryDuplicate(UnityEngine.Texture2D original, int width, int height) { UnityEngine.Texture2D result; if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original) { result = null; } else { RenderTexture active = RenderTexture.active; bool flag = !TextureUtil.GetLinearSampled(original); RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, (!flag) ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB); GL.sRGBWrite = (flag && QualitySettings.activeColorSpace == ColorSpace.Linear); Graphics.Blit(original, temporary); GL.sRGBWrite = false; RenderTexture.active = temporary; bool flag2 = width >= SystemInfo.maxTextureSize || height >= SystemInfo.maxTextureSize; UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(width, height, TextureFormat.RGBA32, original.mipmapCount > 1 || flag2); texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0); texture2D.Apply(); RenderTexture.ReleaseTemporary(temporary); EditorGUIUtility.SetRenderTextureNoViewport(active); texture2D.alphaIsTransparency = original.alphaIsTransparency; result = texture2D; } return(result); }
static void RenderSkyBoxFaceToPNG( int orientation, Camera cam, string assetPath ) { // cam.transform.eulerAngles = skyDirection[orientation]; // RenderTexture rt = new RenderTexture ( faceSize, faceSize, 24 ); // cam.camera.targetTexture = rt; // cam.camera.Render (); // RenderTexture.active = rt; // // Texture2D screenShot = new Texture2D ( faceSize, faceSize, TextureFormat.RGB24, false ); // screenShot.ReadPixels ( new Rect ( 0, 0, faceSize, faceSize ), 0, 0 ); // // RenderTexture.active = null; // GameObject.DestroyImmediate ( rt ); cam.transform.eulerAngles = skyDirection[orientation]; cam.GetComponent<Camera>().Render (); Texture2D screenShot = new Texture2D ( Screen.width, Screen.height, TextureFormat.RGB24, false ); screenShot.ReadPixels ( new Rect ( 0, 0, Screen.width, Screen.height ), 0, 0 ); screenShot.Apply (); // screenShot.Resize ( faceSize, faceSize, TextureFormat.ARGB32, false ); TextureScale.Bilinear ( screenShot, faceSize, faceSize ); byte[] bytes = screenShot.EncodeToPNG (); File.WriteAllBytes ( assetPath, bytes ); AssetDatabase.ImportAsset ( assetPath, ImportAssetOptions.ForceUpdate ); }
static int QPYX_ReadPixels_YXQP(IntPtr L_YXQP) { try { int QPYX_count_YXQP = LuaDLL.lua_gettop(L_YXQP); if (QPYX_count_YXQP == 4) { UnityEngine.Texture2D QPYX_obj_YXQP = (UnityEngine.Texture2D)ToLua.CheckObject(L_YXQP, 1, typeof(UnityEngine.Texture2D)); UnityEngine.Rect QPYX_arg0_YXQP = StackTraits <UnityEngine.Rect> .Check(L_YXQP, 2); int QPYX_arg1_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 3); int QPYX_arg2_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 4); QPYX_obj_YXQP.ReadPixels(QPYX_arg0_YXQP, QPYX_arg1_YXQP, QPYX_arg2_YXQP); return(0); } else if (QPYX_count_YXQP == 5) { UnityEngine.Texture2D QPYX_obj_YXQP = (UnityEngine.Texture2D)ToLua.CheckObject(L_YXQP, 1, typeof(UnityEngine.Texture2D)); UnityEngine.Rect QPYX_arg0_YXQP = StackTraits <UnityEngine.Rect> .Check(L_YXQP, 2); int QPYX_arg1_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 3); int QPYX_arg2_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 4); bool QPYX_arg3_YXQP = LuaDLL.luaL_checkboolean(L_YXQP, 5); QPYX_obj_YXQP.ReadPixels(QPYX_arg0_YXQP, QPYX_arg1_YXQP, QPYX_arg2_YXQP, QPYX_arg3_YXQP); return(0); } else { return(LuaDLL.luaL_throw(L_YXQP, "invalid arguments to method: UnityEngine.Texture2D.ReadPixels")); } } catch (Exception e_YXQP) { return(LuaDLL.toluaL_exception(L_YXQP, e_YXQP)); } }
/// <summary> /// Sets up a copy of the subject, and creates a image from a camera positioned according to this instance's values /// </summary> /// <param name="width">The output image width, in pixels</param> /// <param name="height">The output image height, in pixels</param> /// <returns></returns> public Texture2D RenderPreview(int width, int height) { //validation if (width <= 0) { throw new ArgumentOutOfRangeException("width"); } if (height <= 0) { throw new ArgumentOutOfRangeException("height"); } var cameraObject = new GameObject("__catalog_preview_camera"); var pivot = new GameObject("__catalog_preview_pivot"); cameraObject.hideFlags = HideFlags.DontSave; pivot.hideFlags = HideFlags.DontSave; cameraObject.transform.parent = pivot.transform; var camera = cameraObject.AddComponent<Camera>(); camera.clearFlags = CameraClearFlags.SolidColor; camera.backgroundColor = MatteColor; //must record active state to be able to instantiate disabled object //otherwise undesired scripts might run var wasActive = _subject.Model.activeSelf; _subject.Model.SetActive(false); var objectToRender = (GameObject) Object.Instantiate(_subject.Model, Vector3.zero, Quaternion.identity); objectToRender.name = "__catalog_preview_subject"; _subject.Model.SetActive(wasActive); DisableScriptsInHierarchy(objectToRender); objectToRender.SetActive(true); //position camera and pivot objectToRender.transform.position = RenderSetupPosition; pivot.transform.position = RenderSetupPosition; camera.transform.localPosition = Vector3.forward * DistanceToPivot; camera.transform.LookAt(objectToRender.transform); pivot.transform.position += PivotPosition; pivot.transform.rotation = PivotRotation; camera.aspect = width / (float)height; //do render int ow = width * OverscaleRender, oh = height * OverscaleRender; var output = new RenderTexture(ow, oh, 32); RenderTexture.active = output; camera.targetTexture = output; camera.Render(); //export image var image = new Texture2D(ow, oh, TextureFormat.ARGB32, false); image.ReadPixels(new Rect(0, 0, ow, oh), 0, 0); TextureScale.Bilinear(image, width, height); image.alphaIsTransparency = true; //cleanup RenderTexture.active = null; camera.targetTexture = null; DestroyImmediate(output); DestroyImmediate(cameraObject); DestroyImmediate(pivot); DestroyImmediate(objectToRender); return image; }
public static Texture2D GeneratePreview(Object obj, int width, int height) { Texture2D tex = null; GameObject go = obj as GameObject; if(PrepareCamera(previewCamera, go, width, height)) { go = GameObject.Instantiate(go); go.transform.position = Vector3.zero; RenderTexture renderTexture = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Default, 1); RenderTexture.active = renderTexture; previewCamera.targetTexture = renderTexture; previewCamera.Render(); tex = new Texture2D(width, height); tex.ReadPixels(new Rect(0,0,renderTexture.width,renderTexture.height), 0, 0); tex.Apply(); RenderTexture.ReleaseTemporary(renderTexture); pb_ObjectUtility.Destroy(go); } return tex; }
void OnRenderImage (RenderTexture source, RenderTexture destination){ Graphics.Blit(source,destination,mat); //mat is the material which contains the shader //we are passing the destination RenderTexture to int width = Screen.width; int height = Screen.height; Debug.Log (width.ToString ()); Debug.Log (height.ToString ()); Texture2D tex = new Texture2D(width, height); tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); if (flag == true) { string[] blue = new string[width * height]; for (int i = 0; i < height; i++) { for (int j=0; j < width; j++) { blue[(i * width) + j] = tex.GetPixel (j, i).b.ToString (); } } string output = string.Join(",", blue); File.WriteAllText ("/Users/mettinger/Desktop/temp/output.txt", output); flag = false; } Debug.Log (tex.GetPixel(x,y).b.ToString()); }
void cropImage() { RectTransform zona = area.GetComponent<RectTransform> (); RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 24); cam.targetTexture = rt; cam.Render(); RenderTexture.active = rt; Texture2D image = new Texture2D((int)(zona.rect.width*canvas.scaleFactor), (int)(zona.rect.height*canvas.scaleFactor)); /*string debug = "ScreenW: " + Screen.width + " ScreenH: " + Screen.height+"\n"; debug += "Pos: " + zona.position + " pos2: " + zona.rect.position+"\n"; debug += "xMin: " + zona.rect.xMin + " xMax: " + zona.rect.xMax+" "; debug += "yMin: " + zona.rect.yMin + " yMax: " + zona.rect.yMax+"\n"; debug += "Pos: "+ (zona.position.x + zona.rect.xMin)+", "+(zona.position.y - zona.rect.yMin)+" width: "+zona.rect.width+" height: "+zona.rect.height+"\n"; debug += "ScaleFactor: "+canvas.scaleFactor+"\n"; debug += "Pos: "+ (zona.position.x + zona.rect.xMin)+", "+(zona.position.y - zona.rect.yMin)+" width: "+zona.rect.width+" height: "+zona.rect.height+"\n"; debug += "Pos: "+ (zona.position.x*canvas.scaleFactor+zona.rect.xMin*canvas.scaleFactor)+", "+(Screen.height*canvas.scaleFactor-(zona.position.y *canvas.scaleFactor + zona.rect.yMax *canvas.scaleFactor))+" width: "+(zona.rect.width*canvas.scaleFactor)+" height: "+(zona.rect.height*canvas.scaleFactor)+"\n";*/ //#if UNITY_EDITOR image.ReadPixels(new Rect(zona.position.x+zona.rect.xMin*canvas.scaleFactor, Screen.height-(zona.position.y + zona.rect.yMax *canvas.scaleFactor), zona.rect.width*canvas.scaleFactor, zona.rect.height*canvas.scaleFactor), 0, 0); //else //image.ReadPixels(new Rect(zona.position.x+zona.rect.xMin*canvas.scaleFactor, (zona.position.y + zona.rect.yMin*canvas.scaleFactor), zona.rect.width*canvas.scaleFactor, zona.rect.height*canvas.scaleFactor), 0, 0); //#endif image.Apply(); Data.Instance.lastArtTexture = image; //debugText.text = debug; Data.Instance.LoadLevel("confirmArtworkSize"); }
IEnumerator PostScreenshot() { yield return new WaitForEndOfFrame(); var cam = Camera.current; var renderTexture = new RenderTexture(Screen.width, Screen.height, 24); cam.targetTexture = renderTexture; cam.Render(); cam.targetTexture = null; Texture2D screenshot = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false); screenshot.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); screenshot.Apply(); Debug.Log("Screenshot taken..."); Imvu.Login().Then( userModel => userModel.GetPersonalFeed() ).Then( feedCollection => { return feedCollection.PostImage(screenshot); } ).Then( _ => Debug.Log("Screenshot posted!") ).Catch( error => Debug.Log(error.message) ); }
public static UnityTexture2D CreateTemporaryDuplicate(UnityTexture2D original, int width, int height) { if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original) { return(null); } RenderTexture save = RenderTexture.active; RenderTexture tmp = RenderTexture.GetTemporary( width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.sRGB); Graphics.Blit(original, tmp); RenderTexture.active = tmp; // If the user system doesn't support this texture size, force it to use mipmap bool forceUseMipMap = width >= SystemInfo.maxTextureSize || height >= SystemInfo.maxTextureSize; UnityTexture2D copy = new UnityTexture2D(width, height, TextureFormat.RGBA32, original.mipmapCount > 1 || forceUseMipMap); copy.ReadPixels(new Rect(0, 0, width, height), 0, 0); copy.Apply(); RenderTexture.ReleaseTemporary(tmp); copy.alphaIsTransparency = original.alphaIsTransparency; return(copy); }
public static void Encode(Texture2D src, Texture2D dst, bool gpu = false, YCgACoFormat format = YCgACoFormat.CgACoY_DontChange, int quality = 100) { var pixels = src.GetPixels(); Resize(src, dst, format); var resized = src.width != dst.width || src.height != dst.height; if (gpu) { // TODO: Force mipmap and trilinear when resized. var shader = Shader.Find("Hidden/RGBA to CgACoY"); var mat = new Material(shader); var temp = RenderTexture.GetTemporary(dst.width, dst.height); Graphics.Blit(src, temp, mat); dst.ReadPixels(new Rect(0, 0, dst.width, dst.height), 0, 0); RenderTexture.ReleaseTemporary(temp); Object.DestroyImmediate(mat); } else { if (resized) { var srcPixels = pixels; pixels = dst.GetPixels(); Shrink(srcPixels, pixels, src.width, dst.width); } RGBAToCgACoY(pixels, pixels); dst.SetPixels(pixels); } Compress(dst, format, quality); }
IEnumerator ScreenshotEncode() { #if UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX // wait for graphics to render yield return new WaitForEndOfFrame(); // create a texture to pass to encoding Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false); // put buffer into texture texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); texture.Apply(); // split the process up--ReadPixels() and the GetPixels() call inside of the encoder are both pretty heavy yield return 0; byte[] bytes = texture.EncodeToPNG(); // save our test image (could also upload to WWW) File.WriteAllBytes(path + "/" + imageNamePrefix + DateTime.Now.ToString("MM-dd-yyyy_hh-mm-ss") + ".png", bytes); Debug.Log("Took Screen Shot"); // Added by Karl. - Tell unity to delete the texture, by default it seems to keep hold of it and memory crashes will occur after too many screenshots. DestroyObject(texture); canTakeScreenShot = true; #else return null; #endif }
/// <summary> /// Takes a map snapshot and saves it /// </summary> public void TakeSnapshot() { //TODO fix this for webplayer #if !UNITY_WEBPLAYER //setup rendertexture RenderTexture rt = new RenderTexture(resWidth, resHeight, 24); rt.antiAliasing = msaa; rt.filterMode = FilterMode.Trilinear; GetComponent<Camera>().targetTexture = rt; //render the texture Texture2D snapshot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); GetComponent<Camera>().Render(); RenderTexture.active = rt; snapshot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0); GetComponent<Camera>().targetTexture = null; RenderTexture.active = null; DestroyImmediate(rt); byte[] bytes = snapshot.EncodeToPNG(); DestroyImmediate(snapshot); //save to the file if (!System.IO.Directory.Exists(GetFullFolderPath())) { Debug.LogError("File path: " + GetFullFolderPath() + " doesn't exist! Create it."); return; } string _fileName = SnapshotName(resWidth, resHeight); System.IO.File.WriteAllBytes(_fileName, bytes); MUtil.Log(string.Format("Saved snapshot to: {0}", _fileName), this); _fileName = ""; #endif }
/// <summary> /// If the camera has a render texture, save its contents into the specified file using PNG image format. /// </summary> static public bool SaveRenderTextureAsPNG (this Camera cam, string filename) { // Render textures only work in Unity Pro if (!UnityEditorInternal.InternalEditorUtility.HasPro()) return false; RenderTexture rt = cam.targetTexture; if (rt == null) return false; // Read the render texture's contents into the 2D texture RenderTexture.active = rt; Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false); tex.hideFlags = HideFlags.HideAndDontSave; tex.ReadPixels(new Rect(0f, 0f, rt.width, rt.height), 0, 0); tex.Apply(); RenderTexture.active = null; try { // Save the contents into the specified PNG byte[] bytes = tex.EncodeToPNG(); FileStream fs = File.OpenWrite(filename); fs.Write(bytes, 0, bytes.Length); fs.Close(); } catch (System.Exception ex) { Debug.LogError(ex.Message); return false; } finally { NGUITools.DestroyImmediate(tex); } return true; }
Texture2D Capture(Camera camera, Rect rect) { // 创建一个RenderTexture对象 RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0); // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机 camera.targetTexture = rt; camera.Render(); //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。 //ps: camera2.targetTexture = rt; //ps: camera2.Render(); //ps: ------------------------------------------------------------------- // 激活这个rt, 并从中中读取像素。 RenderTexture.active = rt; Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false); screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素 screenShot.Apply(); // 重置相关参数,以使用camera继续在屏幕上显示 camera.targetTexture = null; //ps: camera2.targetTexture = null; RenderTexture.active = null; // JC: added to avoid errors GameObject.Destroy(rt); // 最后将这些纹理数据,成一个png图片文件 byte[] bytes = screenShot.EncodeToPNG(); string filename = Application.dataPath + "/Screenshot.png"; System.IO.File.WriteAllBytes(filename, bytes); Debug.Log(string.Format("截屏了一张照片: {0}", filename)); return screenShot; }
IEnumerator Screenshot() { if (!Directory.Exists(outPath)) { Directory.CreateDirectory(outPath); } while (record) { /*counter++; Application.CaptureScreenshot(outPath + counter.ToString("D8") + ".png", 0); UnityEngine.Debug.Log("PNG Created " + counter); yield return new WaitForSeconds(recordStep);*/ counter++; RenderTexture rt = new RenderTexture(resWidth, resHeight, 24); camera.targetTexture = rt; Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); camera.Render(); RenderTexture.active = rt; screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0); camera.targetTexture = null; RenderTexture.active = null; // JC: added to avoid errors Destroy(rt); byte[] bytes = screenShot.EncodeToPNG(); string filename = outPath + counter.ToString("D8") + ".png";//8 didget naming scheme limits us to videos roughly 28.9 days long System.IO.File.WriteAllBytes(filename, bytes); UnityEngine.Debug.Log(string.Format("Took screenshot to: {0}", filename)); yield return new WaitForSeconds(recordStep); } yield break; }
/// <summary> /// 对相机截图。 /// </summary> /// <returns>The screenshot2.</returns> /// <param name="camera">Camera.要被截屏的相机</param> /// <param name="rect">Rect.截屏的区域</param> Texture2D CaptureCamera(Camera camera, Rect rect) { // 创建一个RenderTexture对象 Debug.Log(rect.width + " " + rect.height); RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0); // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机 camera.targetTexture = rt; camera.Render(); //--- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。 //camera2.targetTexture = rt; //camera2.Render(); //------------------------------------------------------------------- // 激活这个rt, 并从中中读取像素。 RenderTexture.active = rt; Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false); screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素 screenShot.Apply(); // 重置相关参数,以使用camera继续在屏幕上显示 camera.targetTexture = null; //ps: camera2.targetTexture = null; RenderTexture.active = null; // JC: added to avoid errors GameObject.Destroy(rt); CacheFactory.SaveToPicture(screenShot, "/ScreenShot.png",CacheFactory.PictureType.JPG); return screenShot; }
public IEnumerator TakeScreenShot() { yield return new WaitForEndOfFrame(); Camera camOV = OVcamera.GetComponent<Camera>(); RenderTexture currentRT = RenderTexture.active; RenderTexture.active = camOV.targetTexture; camOV.Render(); Texture2D imageOverview = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false); imageOverview.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0); imageOverview.Apply(); RenderTexture.active = currentRT; // Encode texture into PNG byte[] bytes = imageOverview.EncodeToPNG(); // save in memory //string filename = fileName(Convert.ToInt32(imageOverview.width), Convert.ToInt32(imageOverview.height)); string filename = fileName(resWidth, resHeight); //path = Application.persistentDataPath + "/Snapshots/" + filename; path = filename; System.IO.File.WriteAllBytes(path, bytes); }
// вызывается из потока событий unity static private PacketShootReady shoot(PacketHeader packet) { if (activecamera != "") { int w = 1280; int h = 720; UnityEngine.GameObject obj = cameras[idnames[activecamera]]; UnityEngine.Camera camera = obj.GetComponent <UnityEngine.Camera>(); UnityEngine.Texture2D image = new UnityEngine.Texture2D(w, h, UnityEngine.TextureFormat.RGB24, false); UnityEngine.RenderTexture texture = new UnityEngine.RenderTexture(w, h, 0); UnityEngine.RenderTexture.active = texture; camera.targetTexture = texture; camera.Render(); image.ReadPixels(new UnityEngine.Rect(0, 0, w, h), 0, 0); image.Apply(); byte[] jpg = UnityEngine.ImageConversion.EncodeToJPG(image); camera.targetTexture = null; UnityEngine.RenderTexture.active = null; UnityEngine.Object.Destroy(image); return(new PacketShootReady(1, Convert.ToBase64String(jpg))); } return(new PacketShootReady(0, "")); }
static int ReadPixels(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 4 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Rect), typeof(int), typeof(int))) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1); UnityEngine.Rect arg0 = (UnityEngine.Rect)ToLua.ToObject(L, 2); int arg1 = (int)LuaDLL.lua_tonumber(L, 3); int arg2 = (int)LuaDLL.lua_tonumber(L, 4); obj.ReadPixels(arg0, arg1, arg2); return(0); } else if (count == 5 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Rect), typeof(int), typeof(int), typeof(bool))) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1); UnityEngine.Rect arg0 = (UnityEngine.Rect)ToLua.ToObject(L, 2); int arg1 = (int)LuaDLL.lua_tonumber(L, 3); int arg2 = (int)LuaDLL.lua_tonumber(L, 4); bool arg3 = LuaDLL.lua_toboolean(L, 5); obj.ReadPixels(arg0, arg1, arg2, arg3); return(0); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Texture2D.ReadPixels")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public static UnityTexture2D RenderStaticPreview(Sprite sprite, Color color, int width, int height, Matrix4x4 transform) { if (sprite == null) { return(null); } PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int)sprite.rect.width, (int)sprite.rect.height, ref width, ref height); SavedRenderTargetState savedRTState = new SavedRenderTargetState(); RenderTexture tmp = RenderTexture.GetTemporary(width, height, 0, SystemInfo.GetGraphicsFormat(DefaultFormat.LDR)); RenderTexture.active = tmp; GL.Clear(true, true, new Color(0f, 0f, 0f, 0.1f)); previewSpriteDefaultMaterial.mainTexture = sprite.texture; previewSpriteDefaultMaterial.SetPass(0); RenderSpriteImmediate(sprite, color, transform); UnityTexture2D copy = new UnityTexture2D(width, height, TextureFormat.ARGB32, false); copy.hideFlags = HideFlags.HideAndDontSave; copy.ReadPixels(new Rect(0, 0, width, height), 0, 0); copy.Apply(); RenderTexture.ReleaseTemporary(tmp); savedRTState.Restore(); return(copy); }
void LateUpdate() { takeHiResShot |= Input.GetKeyDown("joystick button 0"); if (takeHiResShot) { if (photos.Count >= 5) { Debug.Log("Too many photos, not saving"); takeHiResShot = false; return; } RenderTexture rt = new RenderTexture(resWidth, resHeight, 24); camera.targetTexture = rt; Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); camera.Render(); RenderTexture.active = rt; screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0); camera.targetTexture = null; RenderTexture.active = null; // JC: added to avoid errors Destroy(rt); byte[] bytes = screenShot.EncodeToPNG(); string filename = ScreenShotName(resWidth, resHeight); photos.Add(bytes); takeHiResShot = false; Debug.Log(string.Format("Added screenshot to memory. {0} photos in total now.", photos.Count)); Texture2D texture = new Texture2D(resWidth, resHeight); texture.LoadImage(bytes); } }
public static UnityEngine.Texture2D CreateTemporaryDuplicate(UnityEngine.Texture2D original, int width, int height) { UnityEngine.Texture2D result; if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original) { result = null; } else { RenderTexture active = RenderTexture.active; Rect rawViewportRect = ShaderUtil.rawViewportRect; RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.sRGB); Graphics.Blit(original, temporary, EditorGUIUtility.GUITextureBlit2SRGBMaterial); RenderTexture.active = temporary; bool flag = width >= SystemInfo.maxTextureSize || height >= SystemInfo.maxTextureSize; UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(width, height, TextureFormat.RGBA32, original.mipmapCount > 1 || flag); texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0); texture2D.Apply(); RenderTexture.ReleaseTemporary(temporary); EditorGUIUtility.SetRenderTextureNoViewport(active); ShaderUtil.rawViewportRect = rawViewportRect; texture2D.alphaIsTransparency = original.alphaIsTransparency; result = texture2D; } return(result); }
public static UnityEngine.Texture2D RenderStaticPreview(Sprite sprite, Color color, int width, int height, Matrix4x4 transform) { UnityEngine.Texture2D result; if (sprite == null) { result = null; } else { PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int)sprite.rect.width, (int)sprite.rect.height, ref width, ref height); SavedRenderTargetState savedRenderTargetState = new SavedRenderTargetState(); RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Default); RenderTexture.active = temporary; GL.Clear(true, true, new Color(0f, 0f, 0f, 0.1f)); SpriteUtility.previewSpriteDefaultMaterial.mainTexture = sprite.texture; SpriteUtility.previewSpriteDefaultMaterial.SetPass(0); SpriteUtility.RenderSpriteImmediate(sprite, color, transform); UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(width, height, TextureFormat.ARGB32, false); texture2D.hideFlags = HideFlags.HideAndDontSave; texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0); texture2D.Apply(); RenderTexture.ReleaseTemporary(temporary); savedRenderTargetState.Restore(); result = texture2D; } return(result); }
static public int ReadPixels(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if (argc == 4) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Rect a1; checkValueType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); self.ReadPixels(a1, a2, a3); pushValue(l, true); return(1); } else if (argc == 5) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Rect a1; checkValueType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Boolean a4; checkType(l, 5, out a4); self.ReadPixels(a1, a2, a3, a4); pushValue(l, true); return(1); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function ReadPixels to call"); return(2); } catch (Exception e) { return(error(l, e)); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif }
/// <summary> /// Call this to capture a custom, screenshot /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static Texture2D CaptureCustomScreenshot(int width, int height) { UnityEngine.Texture2D textured = new UnityEngine.Texture2D(width, height, UnityEngine.TextureFormat.RGB24, true, false); textured.ReadPixels(new UnityEngine.Rect(0f, 0f, (float)width, (float)height), 0, 0); int miplevel = UnityEngine.Screen.width / 800; UnityEngine.Texture2D textured2 = new UnityEngine.Texture2D(width >> miplevel, height >> miplevel, UnityEngine.TextureFormat.RGB24, false, false); textured2.SetPixels32(textured.GetPixels32(miplevel)); textured2.Apply(); return(textured2); }
// вызывается из потока событий unity static private PacketDepthReady depth(PacketHeader packet) { if (activecamera != "") { int w = 1280; int h = 720; UnityEngine.GameObject obj = cameras[idnames[activecamera]]; UnityEngine.Camera camera = obj.GetComponent <UnityEngine.Camera>(); UnityEngine.Texture2D map = new UnityEngine.Texture2D(w, h, UnityEngine.TextureFormat.RGB24, false); UnityEngine.RenderTexture texture = new UnityEngine.RenderTexture(w, h, 0); UnityEngine.RenderTexture.active = texture; camera.targetTexture = texture; obj.GetComponent <camera>().IsdDepth = true; camera.Render(); obj.GetComponent <camera>().IsdDepth = false; map.ReadPixels(new UnityEngine.Rect(0, 0, w, h), 0, 0); map.Apply(); byte[] raw = map.GetRawTextureData(); byte[] floats = new byte[h * w * 4]; for (int y = 0; y < h; y++) { int y_ = h - y - 1; for (int x = 0; x < w; x++) { float depth = raw[(y_ * w + x) * 3 + 0] / 255.0f + raw[(y_ * w + x) * 3 + 1] / 65025.0f + raw[(y_ * w + x) * 3 + 2] / 16581375.0f; depth = (depth == 0.0f || depth == 1.0f) ? 0.0f : camera.nearClipPlane + (camera.farClipPlane - camera.nearClipPlane) * depth; byte[] eb = BitConverter.GetBytes(depth); floats[(y * w + x) * 4 + 0] = BitConverter.IsLittleEndian ? eb[3] : eb[0]; floats[(y * w + x) * 4 + 1] = BitConverter.IsLittleEndian ? eb[2] : eb[1]; floats[(y * w + x) * 4 + 2] = BitConverter.IsLittleEndian ? eb[1] : eb[2]; floats[(y * w + x) * 4 + 3] = BitConverter.IsLittleEndian ? eb[0] : eb[3]; } } camera.targetTexture = null; UnityEngine.RenderTexture.active = null; UnityEngine.Object.Destroy(map); return(new PacketDepthReady(1, Convert.ToBase64String(floats))); } return(new PacketDepthReady(0, "")); }
/// <summary> /// 实际存储方法,存储jpg /// </summary> /// <param name="captureSucceed">存储完执行</param> /// <returns></returns> private IEnumerator Capture() { RectTransform rt = trans_b_grayMask.GetComponent <RectTransform>(); yield return(new WaitForEndOfFrame()); Texture2D te = new Texture2D((int)rt.sizeDelta.x, (int)rt.sizeDelta.y, TextureFormat.ARGB32, false); te.ReadPixels(new Rect(240, 0, te.width, te.height), 0, 0); te.Apply(); //yield return new WaitForSeconds(0.1f); JpgShotEnd(te); }
/// <summary> /// 实际存储方法,存gif /// </summary> /// <param name="index">gif编号</param> /// <param name="captureSucceed">存储完执行</param> /// <returns></returns> private IEnumerator Capture(int index) { RectTransform rt = trans_b_grayMask.GetComponent <RectTransform>(); yield return(new WaitForEndOfFrame()); Texture2D te = new Texture2D((int)rt.sizeDelta.x, (int)rt.sizeDelta.y, TextureFormat.ARGB32, false); te.ReadPixels(new Rect(240, 0, te.width, te.height), 0, 0); te.Apply(); //yield return new WaitForSeconds(0.1f); UserModel.Ins.StoreFXJPGTex(te, index); CameraManager.Instan().CameraResume(); }
private static UnityEngine.Texture2D ToTexture2DNoise(this UnityEngine.RenderTexture inTex, bool apply = true, bool release = false, UnityEngine.TextureFormat format = UnityEngine.TextureFormat.RGBA32) { UnityEngine.Texture2D tex = new UnityEngine.Texture2D(inTex.width, inTex.height, format, false); UnityEngine.RenderTexture.active = inTex; tex.ReadPixels(new UnityEngine.Rect(0, 0, inTex.width, inTex.height), 0, 0); if (release) { UnityEngine.RenderTexture.active = null; inTex.Release(); } if (apply) { tex.Apply(); } return(tex); }
public static int ReadPixels1_wrap(long L) { try { long nThisPtr = FCLibHelper.fc_get_inport_obj_ptr(L); UnityEngine.Texture2D obj = get_obj(nThisPtr); Rect arg0 = new Rect(); FCLibHelper.fc_get_rect(L, 0, ref arg0); int arg1 = FCLibHelper.fc_get_int(L, 1); int arg2 = FCLibHelper.fc_get_int(L, 2); obj.ReadPixels(arg0, arg1, arg2); } catch (Exception e) { Debug.LogException(e); } return(0); }
static public int ReadPixels(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if (argc == 5) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Rect a1; checkValueType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Boolean a4; checkType(l, 5, out a4); self.ReadPixels(a1, a2, a3, a4); pushValue(l, true); return(1); } else if (argc == 4) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Rect a1; checkValueType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); self.ReadPixels(a1, a2, a3); pushValue(l, true); return(1); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int ReadPixels(IntPtr l) { try{ if (matchType(l, 2, typeof(UnityEngine.Rect), typeof(int), typeof(int), typeof(bool))) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Rect a1; checkType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Boolean a4; checkType(l, 5, out a4); self.ReadPixels(a1, a2, a3, a4); return(0); } else if (matchType(l, 2, typeof(UnityEngine.Rect), typeof(int), typeof(int))) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Rect a1; checkType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); self.ReadPixels(a1, a2, a3); return(0); } LuaDLL.luaL_error(l, "No matched override function to call"); return(0); } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return(0); } }
/// <summary> /// Call this to capture a screenshot Automatic size /// </summary> /// <returns></returns> public static byte[] CaptureScreenshot() { UnityEngine.Texture2D textured = new UnityEngine.Texture2D(UnityEngine.Screen.width, UnityEngine.Screen.height, UnityEngine.TextureFormat.RGB24, false, false); textured.ReadPixels(new UnityEngine.Rect(0f, 0f, (float)UnityEngine.Screen.width, (float)UnityEngine.Screen.height), 0, 0); return(textured.EncodeToPNG()); }
internal static UnityEngine.Texture2D BlitTexture(UnityEngine.Texture2D texture, UnityEngine.TextureFormat format, bool alphaOnly = false) { var texPath = AssetDatabase.GetAssetPath(texture); var asset = AssetDatabase.LoadMainAssetAtPath(texPath); RenderTextureReadWrite rtReadWrite = UnityEngine.RenderTextureReadWrite.sRGB; if (asset is Texture2D) { var importer = (TextureImporter)AssetImporter.GetAtPath(texPath); if (importer != null) { rtReadWrite = importer.sRGBTexture ? UnityEngine.RenderTextureReadWrite.sRGB : UnityEngine.RenderTextureReadWrite.Linear; } } // hack to support text mesh pro var fontAssetType = Type.GetType("TMPro.TMP_FontAsset, Unity.TextMeshPro, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); if (fontAssetType != null && fontAssetType.IsInstanceOfType(asset)) { // TMPro texture atlases are always Linear space rtReadWrite = UnityEngine.RenderTextureReadWrite.Linear; } // Create a temporary RenderTexture of the same size as the texture var tmp = UnityEngine.RenderTexture.GetTemporary( texture.width, texture.height, 0, UnityEngine.RenderTextureFormat.Default, rtReadWrite); // Blit the pixels on texture to the RenderTexture UnityEngine.Graphics.Blit(texture, tmp); // Backup the currently set RenderTexture var previous = UnityEngine.RenderTexture.active; // Set the current RenderTexture to the temporary one we created UnityEngine.RenderTexture.active = tmp; // Create a new readable Texture2D to copy the pixels to it var result = new UnityEngine.Texture2D(texture.width, texture.height, format, false); // Copy the pixels from the RenderTexture to the new Texture result.ReadPixels(new UnityEngine.Rect(0, 0, tmp.width, tmp.height), 0, 0); result.Apply(); // Broadcast alpha to color if (alphaOnly || !HasColor(texture)) { var pixels = result.GetPixels(); for (var i = 0; i < pixels.Length; i++) { pixels[i].r = pixels[i].a; pixels[i].g = pixels[i].a; pixels[i].b = pixels[i].a; } result.SetPixels(pixels); result.Apply(); } // Reset the active RenderTexture UnityEngine.RenderTexture.active = previous; // Release the temporary RenderTexture UnityEngine.RenderTexture.ReleaseTemporary(tmp); return(result); }