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 TakeSnapshot() { Texture2D snap = new Texture2D(wct.width, wct.height); snap.SetPixels(wct.GetPixels()); snap.Apply(); texture = snap; string filename = GetNextFilename (); System.IO.File.WriteAllBytes(filename, snap.EncodeToPNG()); UploadPNG(_CaptureCounter.ToString("0000")+".png", snap.EncodeToPNG()); }
// Use this for initialization void Start() { NoiseTextures = new Texture2D[8]; for (int i = 0; i < 8; ++i) { float Seed = Random.Range(0f, 1f); Texture2D NoiseTexture = new Texture2D ((int)Width, (int)Height, TextureFormat.RGBA32, false); Pixels = new Color[(int)(Width * Height)]; for (float y = 0; y < Height; ++y) { for (float x = 0; x < Width; ++x) { float Sample = Mathf.PerlinNoise(x * Scale / Width + Seed, y * Scale / Height + Seed); Pixels[(int)(y * Width + x)] = new Color(Sample, Sample, Sample); } } NoiseTexture.SetPixels (Pixels); NoiseTexture.Apply (); NoiseTextures[i] = NoiseTexture; if (i == 0) { byte[] pngbytes = NoiseTexture.EncodeToPNG(); System.IO.File.WriteAllBytes(Application.dataPath + "\\noise.png", pngbytes); } } }
static void Convert(string origpath, string filename, string destpath) { FSNEditorUtils.MakeTargetDirectory(destpath); // 타겟 경로 확보 var assetpath = destpath + "/" + filename; var absolutepath = Application.dataPath + "/../" + assetpath; //Debug.LogFormat("asset path : {0}, absolute target path : {1}", assetpath, absolutepath); if (AssetDatabase.AssetPathToGUID(assetpath) != null) // 복사하려는 위치에 해당 어셋이 이미 존재한다면 기존 것은 삭제 AssetDatabase.DeleteAsset(assetpath); AssetDatabase.CopyAsset(origpath, assetpath); // 변경하려는 어셋을 복제하여 타겟 경로에 넣는다. AssetDatabase.Refresh(); var texture = AssetDatabase.LoadAssetAtPath<Texture2D>(assetpath); var converted = new Texture2D(texture.width, texture.height, TextureFormat.ARGB32, false); var origcolors = texture.GetPixels32(); var len = origcolors.Length; for (int i = 0; i < len; i++) // 픽셀마다 알파곱 계산 { var color = origcolors[i]; var alpha = (int)color.a; color.r = (byte)(color.r * alpha / 255); color.g = (byte)(color.g * alpha / 255); color.b = (byte)(color.b * alpha / 255); origcolors[i] = color; } converted.SetPixels32(origcolors); System.IO.File.WriteAllBytes(absolutepath, converted.EncodeToPNG()); // 실제 파일로 write AssetDatabase.ImportAsset(assetpath); var importer = AssetImporter.GetAtPath(assetpath) as TextureImporter; // 텍스쳐 옵션 설정 importer.textureType= TextureImporterType.Advanced; importer.alphaIsTransparency = false; // premultiplied alpha texture는 이 옵션을 꺼줘야 한다. importer.SaveAndReimport(); }
// 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 }
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 ); }
/// <summary> /// Saves a texture at the given path /// </summary> public static void SaveTexture(Texture2D tex, string path) { if (!string.IsNullOrEmpty(path)){ byte[] bytes = tex.EncodeToPNG(); File.WriteAllBytes(path, bytes); } }
public static void makeAtlas(Texture2D[] textures) { if (textures != null && textures.Length > 1) { // Make our atlas gameobject with a blank atlas script on it. GameObject go = new GameObject("TEST_ATLAS"); go.AddComponent<Atlas>(); // The blank texture is replaced with the packed texture. Texture2D tex = new Texture2D(2, 2); // Now pack the textures Rect[] UVs = tex.PackTextures(textures, 2, 4096); // Create out spriteAnimation components onto the atlas with height/width equal to the source. for (int i = 0; i < UVs.Length; i++) { SpriteAnimation anim = go.AddComponent<SpriteAnimation>(); anim.setData(textures[i].name, UVs[i]); } FileStream fs = new FileStream(Application.dataPath + "/Resources/Sprites/Atlas_Sprite.png", FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(tex.EncodeToPNG()); bw.Close(); fs.Close(); //PrefabUtility.CreatePrefab(Application.dataPath + "/Resources/Atlases/" + go.name + ".prefab", go); } else { Debug.LogWarning("Given Textures are null or singular."); } }
public static Sprite createSprite(Texture2D tex) { Texture2D newTex = new Texture2D(tex.width, tex.height, TextureFormat.RGBA32, false); newTex.filterMode = FilterMode.Bilinear; newTex.LoadImage(tex.EncodeToPNG()); return Sprite.Create(newTex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100); }
public void SaveTexture(Texture2D tex, string saveAs) { PlayerPrefs.SetString("Image" + saveAs, Convert.ToBase64String(tex.EncodeToPNG())); PlayerPrefs.SetInt("Image" + saveAs + "_w", tex.width); PlayerPrefs.SetInt("Image" + saveAs + "_h", tex.height); PlayerPrefs.Save(); }
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 }
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; }
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); } }
private static void CreateTexture(ProceduralTerrain element) { var path = EditorUtility.SaveFilePanel("Save Texture", string.Empty, "texture.png", "png"); if (string.IsNullOrEmpty(path)) return; var resolution = element.Settings.HeightMapResolution; var texture = new Texture2D(resolution, resolution); for (var z = 0; z < resolution; z++) { for (var x = 0; x < resolution; x++) { var xCoordinate = (element.Settings.Density * x) / resolution; var zCoordinate = (element.Settings.Density * z) / resolution; var noise = 0.5f * (element.NoiseGenerator.Noise(xCoordinate, zCoordinate) + 1); texture.SetPixel(x, z, new Color(noise, noise, noise)); } } // Encode texture into PNG var bytes = texture.EncodeToPNG(); Destroy(texture); //File.WriteAllBytes(Application.dataPath + "/../Perlin.png", bytes); File.WriteAllBytes(path, bytes); }
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); }
/// <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; }
public static void StartShareIntentWithSubject(string caption, string message, string subject, Texture2D texture, string packageNamePattern = "") { byte[] val = texture.EncodeToPNG(); string bytesString = System.Convert.ToBase64String (val); AN_SocialSharingProxy.StartShareIntent(caption, message, subject, bytesString, packageNamePattern); }
// Update is called once per frame void Update () { if (colorMyMang == null) { return; } if (Input.GetButtonDown("Fire1")) { Debug.Log(Input.mousePosition); _ColorManager = colorMyMang.GetComponent<colorMyMang>(); if(_ColorManager == null) { return; } ttt = _ColorManager.GetColorTexture(); Texture2D result = new Texture2D((int)1024, (int)1024); result.SetPixels(ttt.GetPixels(Mathf.FloorToInt(448),Mathf.FloorToInt(28),Mathf.FloorToInt(1024),Mathf.FloorToInt(1024))); //TextureScale.Bilinear(result, 32, 32); TextureScale.Bilinear(result, 32, 32); byte[] bytes = result.EncodeToPNG(); File.WriteAllBytes("SavedScreen.png", bytes); cubeRR.GetComponent<Renderer>().material.mainTexture = ttt; } }
public static Texture2D FromUnityType(UnityEngine.Texture2D texture2D) { return(new Texture2D() { pixels = texture2D.EncodeToPNG(), }); }
void NoiseTexture(int size, bool mono) { var path = EditorUtility.SaveFilePanel("Save Noise Texture", "Assets", "noise" + size, "png"); if (path != "") { var tex = new Texture2D(size, size, TextureFormat.ARGB32, false); var s2 = size * size; var cols = new Color32[s2]; for (int i = 0; i < s2; ++i) { if (mono) { var r = (byte)Random.Range(0, 256); cols[i] = new Color32(r, r, r, 255); } else { cols[i] = new Color32((byte)Random.Range(0, 256), (byte)Random.Range(0, 256), (byte)Random.Range(0, 256), 255); } } tex.SetPixels32(cols); tex.Apply(); System.IO.File.WriteAllBytes(path, tex.EncodeToPNG()); AssetDatabase.Refresh(); Object.DestroyImmediate(tex); path = "Assets" + path.Remove(0, Application.dataPath.Length); // tex = (Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)); TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter; textureImporter.textureFormat = TextureImporterFormat.ARGB32; textureImporter.anisoLevel = 0; AssetDatabase.ImportAsset(path); // EditorUtility.CompressTexture(tex, TextureFormat.ARGB32, 0); //tex.format = TextureFormat.ARGB32; } }
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 } }
/// <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 }
private void GrabSingleView(EditorWindow view, FileInfo targetFile, OutputFormat format) { var width = Mathf.FloorToInt(view.position.width); var height = Mathf.FloorToInt(view.position.height); Texture2D screenShot = new Texture2D(width, height); this.HideOnGrabbing(); var colorArray = InternalEditorUtility.ReadScreenPixel(view.position.position, width, height); screenShot.SetPixels(colorArray); byte[] encodedBytes = null; if (format == OutputFormat.jpg) { encodedBytes = screenShot.EncodeToJPG(); } else { encodedBytes = screenShot.EncodeToPNG(); } File.WriteAllBytes(targetFile.FullName, encodedBytes); this.ShowAfterHiding(); }
void OnWizardCreate() { int potWidth = 1; while (potWidth < frameWidth * frames) potWidth *= 2; int potHeight = 1; while (potHeight < frameHeight) potHeight *= 2; Texture2D texture = new Texture2D(potWidth, potHeight); for (int i = 0; i < frameWidth * frames; i++) { for (int j = 0; j < frameHeight; j++) { if (i % frameWidth == 0 || i % frameWidth == frameWidth - 1 || j == 0 || j == frameHeight - 1) texture.SetPixel(i, j, gridColor); else texture.SetPixel(i, j, backColor); } } File.WriteAllBytes(AssetDatabase.GetAssetPath(Selection.activeObject) + "/" + textureName + ".png", texture.EncodeToPNG()); AssetDatabase.Refresh(); }
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 static string SaveFilePng(Texture2D tx, string name) { byte[] bytes = tx.EncodeToPNG(); UnityEngine.Object.Destroy(tx); File.WriteAllBytes(name, bytes); return name; }
// Update is called once per frame void Update() { img = camTex.GetPixels32(); Texture2D texture = new Texture2D(camTex.width, camTex.height); texture.SetPixels32(img); //send screenshot if (Input.GetKeyDown(KeyCode.Space)){ //convert Texture2D tex2d = new Texture2D(camTex.width, camTex.height); tex2d.SetPixels32(img); byte[] bytes = tex2d.EncodeToPNG(); //send data StartCoroutine("accessToServer", bytes); //accessToServer(bytes); print("finish capture and send"); } //debug else if (Input.GetKeyDown(KeyCode.Q)) { result_txt = "test_txt"; camTex.Stop(); CameraFade.StartAlphaFade(Color.white, false, 1f, 0f, () => { Application.LoadLevel("SummonResultScene"); }); } }
private static Texture2D PersistLookupTexture (string assetName, Texture2D tex) { if (!System.IO.Directory.Exists (kDirectoryName)) System.IO.Directory.CreateDirectory (kDirectoryName); string assetPath = System.IO.Path.Combine (kDirectoryName, assetName + "." + kExtensionName); bool newAsset = !System.IO.File.Exists (assetPath); System.IO.File.WriteAllBytes (assetPath, tex.EncodeToPNG()); AssetDatabase.ImportAsset (assetPath, ImportAssetOptions.ForceUpdate); TextureImporter texSettings = AssetImporter.GetAtPath (assetPath) as TextureImporter; if (!texSettings) { // workaround for bug when importing first generated texture in the project AssetDatabase.Refresh (); AssetDatabase.ImportAsset (assetPath, ImportAssetOptions.ForceUpdate); texSettings = AssetImporter.GetAtPath (assetPath) as TextureImporter; } texSettings.textureFormat = TextureImporterFormat.AutomaticTruecolor; texSettings.wrapMode = TextureWrapMode.Clamp; if (newAsset) AssetDatabase.ImportAsset (assetPath, ImportAssetOptions.ForceUpdate); AssetDatabase.Refresh (); Texture2D newTex = AssetDatabase.LoadAssetAtPath (assetPath, typeof(Texture2D)) as Texture2D; return newTex; }
public static void GenerateBleedTexture() { Object[] selectedTextures = Selection.GetFiltered( typeof(Texture2D), SelectionMode.DeepAssets ); foreach( Object o in selectedTextures ) { Texture2D t = (Texture2D)o; Texture2D bleedTexture = new Texture2D( t.width+8, t.height+8 ); for( int i = 0, ni = bleedTexture.width ; i < ni ; i++ ) { for( int j = 0, nj = bleedTexture.height ; j < nj ; j++ ) { bleedTexture.SetPixel( i, j, t.GetPixelBilinear( (float)(i-4)/t.width, (float)(j-4)/t.height ) ); } } bleedTexture.Apply(); string originalPath = AssetDatabase.GetAssetPath(t); string withoutExtension = originalPath.Split('.')[0]; byte[] bytes = bleedTexture.EncodeToPNG(); System.IO.File.WriteAllBytes(withoutExtension+"Bleed.png", bytes); bytes = null; // Re-import the newly created texture, turning off the 'readable' flag AssetDatabase.Refresh(); } }
// Update is called once per frame void Update() { MetaCoreInterop.meta_get_point_cloud(ref _metaPointCloud, _translation, _rotation); //Added by Yuqi Ding MetaCoreInterop.meta_get_rgb_frame(RawPixelBuffer, _translation, _new_rotation); // The buffer is pre-allocated by constructor. // Check for a difference bool isEqual = true; // Check for a difference in pose (should change with each new RGB frame). for (int i = 0; i < _new_rotation.Length; ++i) { isEqual = _rotation[i] == _new_rotation[i]; if (!isEqual) { break; } } // If the two rotations are not equal, we have a new rgb frame. if (!isEqual) { // Copy new rotation if it's different. for (int i = 0; i < _new_rotation.Length; ++i) { _rotation[i] = _new_rotation[i]; } _rgbTexture.LoadRawTextureData(RawPixelBuffer, _totalBufferSize); _rgbTexture.Apply(); if (Time.frameCount % 48 == 0) { byte[] bytes = _rgbTexture.EncodeToPNG(); string rgbname = string.Format("{0}/{1:D04} shot.png", folder, Time.frameCount); File.WriteAllBytes(rgbname, bytes); } } // Added end SetDepthToWorldTransform(); if (SavePointCloud && (Time.frameCount % 48 == 0)) { MarshalMetaPointCloud(); //UpdateMesh(); int num = _metaPointCloud.num_points; Debug.Log(_translation[0].ToString()); Debug.Log(_translation[1].ToString()); Debug.Log(_translation[2].ToString()); if (num != 0) { string Name1 = string.Format("{0}/{1:D04} shot.ply", folder, Time.frameCount); SavePointCloudToPly(Name1, _pointCloud); } } }
public static VrmLib.Image ToPngImage(this UnityEngine.Texture2D texture, VrmLib.ImageUsage imageUsage) { if (texture != null) { return(new VrmLib.Image(texture.name, "image/png", imageUsage, texture.EncodeToPNG())); } else { return(null); } }
static public int EncodeToPNG(IntPtr l) { try { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); var ret = self.EncodeToPNG(); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int EncodeToPNG(IntPtr l) { try{ UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); System.Byte[] ret = self.EncodeToPNG(); pushValue(l, ret); return(1); } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return(0); } }
static int EncodeToPNG(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D)); byte[] o = obj.EncodeToPNG(); ToLua.Push(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public void SaveSharedObject() { if (!Directory.Exists(Path.Combine(Application.persistentDataPath, "MiniMap"))) { Directory.CreateDirectory(Path.Combine(Application.persistentDataPath, "MiniMap")); } byte[] colorTexBytes = Texture2D.EncodeToPNG(); byte[] waypointsTexBytes = m_WaypointsTexture2D.EncodeToPNG(); var sectorName = GetSectorName(this); var colorPath = Path.Combine(Application.persistentDataPath, "MiniMap/Colors_" + sectorName + ".png"); var waypointsPath = Path.Combine(Application.persistentDataPath, "MiniMap/Waypoints_" + sectorName + ".png"); File.WriteAllBytes(colorPath, colorTexBytes); File.WriteAllBytes(waypointsPath, waypointsTexBytes); }
/// <summary> /// Saves texture into plugin dir with supplied name. /// Precondition: texture must be readable /// </summary> /// <param name="texture"></param> /// <param name="name"></param> public static bool SaveToDisk(this UnityEngine.Texture2D texture, string pathInGameData) { // texture format - needs to be ARGB32, RGBA32, RGB24 or Alpha8 var validFormats = new List <TextureFormat> { TextureFormat.Alpha8, TextureFormat.RGB24, TextureFormat.RGBA32, TextureFormat.ARGB32 }; if (!validFormats.Contains(texture.format)) { Log.Write("Texture to be saved has invalid format. Converting to a valid format."); return(CreateReadable(texture).SaveToDisk(pathInGameData)); } if (pathInGameData.StartsWith("/")) { pathInGameData = pathInGameData.Substring(1); } pathInGameData = "/GameData/" + pathInGameData; if (!pathInGameData.EndsWith(".png")) { pathInGameData += ".png"; } try { Log.Verbose("Saving a {0}x{1} texture as '{2}'", texture.width, texture.height, pathInGameData); System.IO.FileStream file = new System.IO.FileStream(KSPUtil.ApplicationRootPath + pathInGameData, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(file); writer.Write(texture.EncodeToPNG()); Log.Verbose("Texture saved as {0} successfully.", pathInGameData); return(true); } catch (Exception e) { Log.Error("Failed to save texture '{0}' due to {1}", pathInGameData, e); return(false); } }
/// <summary> /// Write the specified value using the writer. /// </summary> /// <param name="value">Value.</param> /// <param name="writer">Writer.</param> public override void Write(object value, ISaveGameWriter writer) { UnityEngine.Texture2D texture2D = (UnityEngine.Texture2D)value; writer.WriteProperty("width", texture2D.width); writer.WriteProperty("height", texture2D.height); writer.WriteProperty("rawTextureData", texture2D.EncodeToPNG()); writer.WriteProperty("dimension", texture2D.dimension); writer.WriteProperty("filterMode", texture2D.filterMode); writer.WriteProperty("anisoLevel", texture2D.anisoLevel); writer.WriteProperty("wrapMode", texture2D.wrapMode); #if UNITY_2017_1_OR_NEWER writer.WriteProperty("wrapModeU", texture2D.wrapModeU); writer.WriteProperty("wrapModeV", texture2D.wrapModeV); writer.WriteProperty("wrapModeW", texture2D.wrapModeW); #endif writer.WriteProperty("mipMapBias", texture2D.mipMapBias); writer.WriteProperty("name", texture2D.name); writer.WriteProperty("hideFlags", texture2D.hideFlags); }
public UnityEngine.Texture2D SaveTexture() { UnityEngine.Texture2D t = new UnityEngine.Texture2D(w, h, UnityEngine.TextureFormat.RGB24, false, true); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (IsTransparent(i, j)) { t.SetPixel(i, j, UnityEngine.Color.white); } else { t.SetPixel(i, j, UnityEngine.Color.blue); } } } byte[] bytes = t.EncodeToPNG(); global::System.IO.File.WriteAllBytes(UnityEngine.Application.dataPath + "/fogMap.png", bytes); UnityEngine.GameObject.DestroyImmediate(t); return(t); }
/// <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()); }
private void Write_Texture2DPNG(ref UnityEngine.Texture2D ioData) { byte[] png = ioData.EncodeToPNG(); Write_ByteArray(ref png); }
private void Write_Texture2DPNG(ref SerializedType ioData) { byte[] png = ioData.EncodeToPNG(); Write_ByteArray(ref png); }
private GLexTexture(Texture2D texture) : base() { mTexture = texture; mImporter = (TextureImporter)AssetImporter.GetAtPath(OriginalURL); // texture need to be readable for export if (!mImporter.isReadable) { Debug.LogWarning("GLexTexture.Construct: Setting texture " + Name + " as Readable, or export will fail!"); mImporter.isReadable = true; AssetDatabase.ImportAsset(OriginalURL); mImporter = (TextureImporter)AssetImporter.GetAtPath(OriginalURL); } if (IsARGB32orRGB24) { _dataBytes = mTexture.EncodeToPNG(); } else { _dataBytes = new JPGEncoder(mTexture, GLexConfig.JPEGQuality).GetBytes(); } _dataBinaryKeystring = NamesUtil.GenerateBinaryId(_dataBytes, GLex.Instance.UserName); mTextures.Add(this); }