EncodeToJPG() 공개 메소드

Encodes this texture into JPG format.

public EncodeToJPG ( ) : byte[]
리턴 byte[]
        private void CopyTextureCube(string texturePath, Cubemap cubemap, BabylonTexture babylonTexture)
        {
            if (!babylonScene.AddTextureCube(texturePath))
            {
                return;
            }

            try
            {
                foreach (CubemapFace face in Enum.GetValues(typeof(CubemapFace)))
                {
                    var faceTexturePath = Path.Combine(babylonScene.OutputPath, Path.GetFileNameWithoutExtension(texturePath));

                    switch (face)
                    {
                        case CubemapFace.PositiveX:
                            faceTexturePath += "_px.jpg";
                            break;
                        case CubemapFace.NegativeX:
                            faceTexturePath += "_nx.jpg";
                            break;
                        case CubemapFace.PositiveY:
                            faceTexturePath += "_py.jpg";
                            break;
                        case CubemapFace.NegativeY:
                            faceTexturePath += "_ny.jpg";
                            break;
                        case CubemapFace.PositiveZ:
                            faceTexturePath += "_pz.jpg";
                            break;
                        case CubemapFace.NegativeZ:
                            faceTexturePath += "_nz.jpg";
                            break;
                        default:
                            continue;
                    }

                    var tempTexture = new Texture2D(cubemap.width, cubemap.height, TextureFormat.RGB24, false);

                    tempTexture.SetPixels(cubemap.GetPixels(face));
                    tempTexture.Apply();

                    // Flip faces in cube texture.
                    tempTexture = FlipTexture(tempTexture);

                    File.WriteAllBytes(faceTexturePath, tempTexture.EncodeToJPG());
                }

            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
            }

            var textureName = Path.GetFileNameWithoutExtension(texturePath);
            babylonTexture.name = textureName;
            babylonTexture.isCube = true;
            babylonTexture.level = exportationOptions.ReflectionDefaultLevel;
            babylonTexture.coordinatesMode = 3;
        }
예제 #2
0
    static int EncodeToJPG(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D)))
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                byte[] o = obj.EncodeToJPG();
                ToLua.Push(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(int)))
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                int    arg0 = (int)LuaDLL.lua_tonumber(L, 2);
                byte[] o    = obj.EncodeToJPG(arg0);
                ToLua.Push(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Texture2D.EncodeToJPG"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
예제 #3
0
    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();
    }
예제 #4
0
 static public int EncodeToJPG(IntPtr l)
 {
     try{
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 2)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             System.Byte[] ret = self.EncodeToJPG(a1);
             pushValue(l, ret);
             return(1);
         }
         else if (argc == 1)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Byte[]         ret  = self.EncodeToJPG();
             pushValue(l, ret);
             return(1);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
예제 #5
0
    /// <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;
    }
    /* ----------------------------------------
     * 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");
        }
    }
	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();
	}
예제 #8
0
        public static void SaveTextureAsFile(Texture2D texture, string folder, string prefix, string suffix, ScreenshotConfig screenshotConfig)
        {
            byte[] bytes;
            string extension;

            switch (screenshotConfig.Type)
            {
                case ScreenshotConfig.Format.PNG:
                    bytes = texture.EncodeToPNG();
                    extension = ".png";
                    break;
                case ScreenshotConfig.Format.JPG:
                    bytes = texture.EncodeToJPG();
                    extension = ".jpg";
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            var fileName = prefix + screenshotConfig.Name + "." + screenshotConfig.Width + "x" + screenshotConfig.Height + suffix;
            var imageFilePath = folder + "/" + MakeValidFileName(fileName + extension);

            // ReSharper disable once PossibleNullReferenceException
            (new FileInfo(imageFilePath)).Directory.Create();
            File.WriteAllBytes(imageFilePath, bytes);

            Debug.Log("Image saved to: " + imageFilePath);
        }
예제 #9
0
    public void OnButtonPressed(int id)
    {
        switch(id){
        case 0 :
            Application.Quit();
            break;
        case 1 :

            break;
        case 2 :
            string txt = GameObject.Find("InputField").GetComponent<InputField>().text;

            if(txt != ""){
                client.SendInfo_text(txt);
            }
            break;
        case 3 :
            Debug.Log("IMAGE");

            WebCamTexture raw = GameObject.Find("Main Camera").GetComponent<WebCam>().cam;
            Texture2D t = new Texture2D(raw.width, raw.height);;
            t.SetPixels(raw.GetPixels());

            Debug.Log("T" + raw.width);

            client.SendInfo_image(t.EncodeToJPG(), t.width, t.height);

            break;
        default: break;
        }
    }
 static public int EncodeToJPG(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 1)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             var ret = self.EncodeToJPG();
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 2)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             var ret = self.EncodeToJPG(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
예제 #11
0
	public static void SavePathJPG(string jpgName,Texture2D textureGrid)
	{
		MyLogger.Log (jpgName + " SavePathJPG begin!!!");
		string jpgPath = GetRealPath (jpgName)+".jpg";
		byte[] bytes = textureGrid.EncodeToJPG ();
		File.WriteAllBytes (jpgPath, bytes);
		MyLogger.Log (jpgPath + " SavePathJPG ok!!!");
	}
    byte[] TextureEncodeToBytes(Rect rect)
    {
        var texture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);

        texture.ReadPixels(rect, 0, 0);
        texture.Apply();

        return texture.EncodeToJPG();
    }
예제 #13
0
 public byte[] Capture()
 {
     RenderTexture currentRT = RenderTexture.active;
     RenderTexture.active = cam.targetTexture;
     cam.Render();
     Texture2D image = new Texture2D(cam.targetTexture.width, cam.targetTexture.height);
     image.ReadPixels(new Rect(0, 0, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
     image.Apply();
     RenderTexture.active = currentRT;
     return image.EncodeToJPG();
 }
예제 #14
0
    IEnumerator ReqRecogImg(Texture2D sourceTex)
    {
        // NTTサイトで取得したAPIKEYを指定
        string apikey="547047744738754a4a553175766354513855635349304c7650574a6a32486e69632f4c49464a306d7a5a43";
        // NTTの画像認識サーバーへのリクエストURL
        string url="https://api.apigw.smt.docomo.ne.jp/imageRecognition/v1/recognize?APIKEY="+apikey+"&recog=product-all&numOfCandidates=2";

        //テクスチャをJPG形式のバイナリに変換して、リクエストのボディーに設定
        Texture2D tex2d2 = new Texture2D (sourceTex.width, sourceTex.height);
        tex2d2.SetPixels32 (sourceTex.GetPixels32 ());
        tex2d2.Apply ();
        byte[] bytes = tex2d2.EncodeToJPG ();

        Dictionary<string,string> has = new Dictionary<string,string>();
        has.Add("Content-Type", "application/octet-stream");
        // HTTPリクエスト開始
        WWW www = new WWW(url,bytes,has);

        // サーバーにリクエストを行いレスポンスを待つ
        yield return www;
        Debug.Log(www.text);
        // サーバーから取得したレスポンスのテキストをJSONパーサー(MiniJson)でパースする
        var json = Json.Deserialize (www.text) as Dictionary<string, object>;

        recogName = "unknown";
        if (!json.ContainsKey ("candidates")) {
            recogBFlag = false;
            yield break;
        }
        IList candi = json ["candidates"] as IList;
        if (candi != null) {
            foreach (var obj in candi) {
                var c = obj as IDictionary;

                if(c==null || !c.Contains("detail")){
                    continue;
                }
                IDictionary detail=(IDictionary)c["detail"];
                if(detail!=null){
                    string itemName=(string)detail["itemName"];
                    if(itemName!=null){
                        Debug.Log (itemName);
                        recogName=itemName;
                        break;
                    }

                }

            }
        }
        recogBFlag = false;
    }
    public void ShareImage(Texture2D image, string message, string imageName)
    {
        byte[] imageContent = image.EncodeToJPG();
        WWWForm wwwForm = new WWWForm();
        //Le agrego la informacion
        wwwForm.AddBinaryData("image", imageContent, imageName);
        wwwForm.AddField("message", message);

        if(FB.IsLoggedIn)
        {
            FB.API("me/photos", HttpMethod.POST, CallbackShareImage, wwwForm);
        }
    }
 public byte[] getImage()
 {
     RenderTexture rt = new RenderTexture (resWidth, resHeight, 24);
     GetComponent<Camera>().targetTexture = rt;
     Texture2D screenShot = new Texture2D (resWidth, resHeight, TextureFormat.RGB24, false);
     GetComponent<Camera>().Render ();
     RenderTexture.active = rt;
     screenShot.ReadPixels (new Rect (0, 0, resWidth, resHeight), 0, 0);
     GetComponent<Camera>().targetTexture = null;
     RenderTexture.active = null; // JC: added to avoid errors
     Destroy (rt);
     byte[] bytes = screenShot.EncodeToJPG ();
     return bytes;
 }
예제 #17
0
파일: Utils.cs 프로젝트: nanalucky/Pet46
        //take screen shot then share via intent
        public static IEnumerator TakeScreenshot(string screenShotPath,string screenShotName)
        {
            yield return new WaitForEndOfFrame();

            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();

            byte[] screenshot;

            string[] pathParts = screenShotName.Split('.');

            if(pathParts.Length > 1){
                string format = pathParts.GetValue(1).ToString();
                Debug.Log( " format " + format );
                if(format.Equals("png",StringComparison.Ordinal)){
                    screenshot = tex.EncodeToPNG();
                    Debug.Log( "screen shot set to png format");
                }else if(format.Equals("jpg",StringComparison.Ordinal)){
                    screenshot = tex.EncodeToJPG();
                    Debug.Log( "screen shot set to jpg format");
                }else{
                    screenshot = tex.EncodeToJPG();
                    Debug.Log( "screen shot unknown format default to jpg");
                }
            }else{
                screenshot = tex.EncodeToJPG();
                Debug.Log( "screen shot no format default to jpg");
            }

            //saving to phone storage
            System.IO.File.WriteAllBytes(screenShotPath,screenshot);
        }
예제 #18
0
		IEnumerator CreateScreenshotCR(string path, int quality = 99) {
			bool error = true;
			float wait = Time.time + 0.5f;
			while (wait > Time.time) {
				yield return null; // wait for png actually existing
				if (System.IO.File.Exists(path + ".png")) {
					error = false;
					break;
				}
			}
			if (!error) {
				var texture = new Texture2D(2, 2, TextureFormat.RGB24, false);
				var data = System.IO.File.ReadAllBytes(path + ".png");
				texture.LoadImage(data);
				System.IO.File.WriteAllBytes(path + ".jpg", texture.EncodeToJPG(quality));
				System.IO.File.Delete(path + ".png");
				UnityEngine.Debug.Log("Screenshot: " + path + ".jpg");
			}
			else {
				UnityEngine.Debug.Log("Error creating screenshot! " + path);
				yield break;
			}
		}
예제 #19
0
    public static void SaveTextureToFile(Texture2D texture, string filename, IMAGE_TYPE itype)
    {
        string path = Application.dataPath + "/"+ filename;
        string path2 = Application.persistentDataPath + "/"+ filename;

        if (itype == IMAGE_TYPE.JPG)
        {

        }
        else
        {

        }
        byte[] data;
        switch (itype)
        {

        case IMAGE_TYPE.JPG:
            data = texture.EncodeToJPG();
            Save(path, data);
            break;
        case IMAGE_TYPE.PNG:
            data = texture.EncodeToPNG();
            Save(path, data);
            Logger.Log ("Encoding to PNG");
            break;
        default:
            Logger.Log ("Incorrect IMAGE_TYPE.");
            break;
        }

        #if UNITY_EDITOR
        Logger.Log(path + " : WAS SAVE");
        #else
        Debug.Log (path2 + " : WAS SAVE");
        #endif
    }
예제 #20
0
        public string SaveTexture(Texture2D tex)
        {

            int id = tex.GetInstanceID();
            string name = null;
            if (savecache.TryGetValue(id, out name))
            {
                return name;
            }
#if UNITY_EDITOR
            name = SaveTextureEditor(tex);
            savecache[id] = name;
            return name;
#endif
            if (parser.debug)
                Debug.Log("SaveTexture" + tex.name);
            int i = tex.name.LastIndexOf(".");
            string ext = "png";
            if (i < 0)
            {
                tex.name = tex.name + ".png";
            }
            else
            {
                ext = tex.name.Substring(i + 1);
            }
            if (ext == "png")
            {
                byte[] bs = tex.EncodeToPNG();
                string sha1 = ResLibTool.ComputeHashString(bs);
                name = sha1 + "." + ext;
                bufs[name] = bs;
            }
            else if (ext == "jpg")
            {
                byte[] bs = tex.EncodeToJPG();
                string sha1 = ResLibTool.ComputeHashString(bs);
                name = sha1 + "." + ext;
                bufs[name] = bs;
            }
            else
            {
                throw new Exception("不知道文件类型" + ext);
            }
            savecache[id] = name;
            return name;

        }
예제 #21
0
 private void Write_Texture2DJPG(ref SerializedType ioData)
 {
     byte[] png = ioData.EncodeToJPG();
     Write_ByteArray(ref png);
 }
예제 #22
0
 private void Write_Texture2DJPG(ref UnityEngine.Texture2D ioData)
 {
     byte[] png = ioData.EncodeToJPG();
     Write_ByteArray(ref png);
 }
예제 #23
0
        private void CopyTexture(string texturePath, Texture2D texture2D, BabylonTexture babylonTexture, bool isLightmap = false)
        {
            string rename = null;
            bool needToDelete = false;
            // Convert unsupported file extensions
            if (texturePath.EndsWith(".psd") || texturePath.EndsWith(".tif") || texturePath.EndsWith(".exr"))
            {
                string srcTexturePath = AssetDatabase.GetAssetPath(texture2D);
                var importTool = new BabylonTextureImporter(srcTexturePath);
                var previousConvertToNormalmap = importTool.textureImporter.convertToNormalmap;
                var previousAlphaSource = importTool.textureImporter.alphaSource;
                var previousTextureType = importTool.textureImporter.textureType;
                importTool.SetReadable();
                importTool.textureImporter.textureType = (isLightmap) ? TextureImporterType.Lightmap : TextureImporterType.Default;
                importTool.textureImporter.alphaSource = TextureImporterAlphaSource.FromInput;
                importTool.textureImporter.convertToNormalmap = false;
                AssetDatabase.ImportAsset(texturePath);

                try
                {
                    var usePNG = texture2D.alphaIsTransparency;
                    var tempTexture = new Texture2D(texture2D.width, texture2D.height, TextureFormat.ARGB32, false);
                    if (isLightmap)
                    {
                        rename = SceneName + Path.GetFileName(texturePath);
                        Color[] pixels = texture2D.GetPixels(0, 0, texture2D.width, texture2D.height);
                        for (int index = 0; index < pixels.Length; index++)
                        {
                            pixels[index].r = pixels[index].r * pixels[index].a * 5;
                            pixels[index].g = pixels[index].g * pixels[index].a * 5;
                            pixels[index].b = pixels[index].b * pixels[index].a * 5;
                        }
                        tempTexture.SetPixels(pixels);
                    }
                    else
                    {
                        Color[] pixels = texture2D.GetPixels(0, 0, texture2D.width, texture2D.height);
                        for (int index = 0; index < pixels.Length; index++)
                        {
                            usePNG |= pixels[index].a <= 0.99999f;
                        }
                        tempTexture.SetPixels32(texture2D.GetPixels32());
                    }
                    tempTexture.Apply();
                    string outputfile = (!String.IsNullOrEmpty(rename)) ? rename : texturePath;
                    texturePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(outputfile));
                    var extension = (usePNG || exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG) ? ".png" : ".jpg";
                    texturePath = texturePath.Replace(".psd", extension).Replace(".tif", extension).Replace(".exr", extension);
                    File.WriteAllBytes(texturePath, (usePNG || exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG) ? tempTexture.EncodeToPNG() : tempTexture.EncodeToJPG(exportationOptions.DefaultQualityLevel));
                    needToDelete = true;
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                }
                finally
                {
                    importTool.textureImporter.textureType = previousTextureType;
                    importTool.textureImporter.alphaSource = previousAlphaSource;
                    importTool.textureImporter.convertToNormalmap = previousConvertToNormalmap;
                    importTool.ForceUpdate();
                }
            }
            else if (texture2D.alphaIsTransparency || texturePath.EndsWith(".png"))
            {
                babylonTexture.hasAlpha = true;
            }
            else
            {
                babylonTexture.hasAlpha = false;
            }
            var textureName = Path.GetFileName(texturePath);
            babylonTexture.name = textureName;
            babylonScene.AddTexture(texturePath);
            if (needToDelete) File.Delete(texturePath);
        }
 void WriteJPGTexture(Texture2D texture,TextureFormat format,string path,string extension)
 {
     EditorUtility.CompressTexture (texture,format,TextureCompressionQuality.Best);
     byte[] jpgData=texture.EncodeToJPG();
     //var nPath=path.Substring(0,path.LastIndexOf('.'))+extension;
     var writePath = Application.dataPath+(path.Substring(0,path.LastIndexOf('.'))+extension).Substring(6);
     File.WriteAllBytes(writePath, jpgData);
     AssetDatabase.SaveAssets();
     AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
 }
        private void CopyTexture(string texturePath, Texture2D texture2D, BabylonTexture babylonTexture)
        {
            bool needToDelete = false;
            var useJPG = !texture2D.alphaIsTransparency;

            // Convert unsupported file extensions
            if (texturePath.EndsWith(".psd") || texturePath.EndsWith(".tif") || texturePath.EndsWith(".exr"))
            {
                try
                {
                    // Change texture import settings to be able to read texture data
                    var textureImporter = AssetImporter.GetAtPath(texturePath) as TextureImporter;
                    var previousIsReadable = textureImporter.isReadable;
                    var previousNormalMap = textureImporter.normalmap;
                    var previousLightmap = textureImporter.lightmap;
                    var previousConvertToNormalmap = textureImporter.convertToNormalmap;
                    var previousTextureType = textureImporter.textureType;
                    var previousGrayscaleToAlpha = textureImporter.grayscaleToAlpha;
                    textureImporter.textureType = TextureImporterType.Advanced;
                    textureImporter.isReadable = true;
                    textureImporter.lightmap = false;
                    textureImporter.normalmap = false;
                    textureImporter.convertToNormalmap = false;
                    textureImporter.grayscaleToAlpha = false;

                    AssetDatabase.ImportAsset(texturePath);

                    texturePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(texturePath));
                    var extension = useJPG ? ".jpg" : ".png";
                    texturePath = texturePath.Replace(".psd", extension).Replace(".tif", extension).Replace(".exr", extension);

                    var tempTexture = new Texture2D(texture2D.width, texture2D.height, TextureFormat.ARGB32, false);

                    tempTexture.SetPixels32(texture2D.GetPixels32());
                    tempTexture.Apply();

                    File.WriteAllBytes(texturePath, useJPG ? tempTexture.EncodeToJPG() : tempTexture.EncodeToPNG());

                    needToDelete = true;

                    // Restore
                    textureImporter.isReadable = previousIsReadable;
                    textureImporter.normalmap = previousNormalMap;
                    textureImporter.lightmap = previousLightmap;
                    textureImporter.convertToNormalmap = previousConvertToNormalmap;
                    textureImporter.textureType = previousTextureType;
                    textureImporter.grayscaleToAlpha = previousGrayscaleToAlpha;
                   
                    AssetDatabase.ImportAsset(texturePath, ImportAssetOptions.ForceUpdate);
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                }
            }

            var textureName = Path.GetFileName(texturePath);
            babylonTexture.name = textureName;
            babylonScene.AddTexture(texturePath);

            if (needToDelete)
            {
                File.Delete(texturePath);
            }
        }
예제 #26
0
 private void CopyTextureFace(string texturePath, string textureName, Texture2D textureFace)
 {
     if (!babylonScene.AddTextureCube(textureName))
     {
         return;
     }
     bool png = (exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG);
     bool textureNotExistsMode = (SceneController != null && SceneController.skyboxOptions.textureFile == BabylonTextureExport.IfNotExists);
     bool writeTextureFile = true;
     if (textureNotExistsMode && File.Exists(texturePath))
     {
         writeTextureFile = false;
         ExporterWindow.ReportProgress(1, "Texture cube item exists: " + textureName);
     }
     if (writeTextureFile)
     {
         var srcTexturePath = AssetDatabase.GetAssetPath(textureFace);
         if ((png && srcTexturePath.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) || (!png && (srcTexturePath.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || srcTexturePath.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase))))
         {
             ExporterWindow.ReportProgress(1, "Copying texture cube item: " + textureName);
             File.Copy(srcTexturePath, texturePath, true);
         }
         else
         {
             if (textureFace != null)
             {
                 var importTool = new BabylonTextureImporter(srcTexturePath);
                 bool isReadable = importTool.IsReadable();
                 if (!isReadable) importTool.SetReadable();
                 try
                 {
                     ExporterWindow.ReportProgress(1, "Exporting texture cube item: " + textureName);
                     var tempTexture = new Texture2D(textureFace.width, textureFace.height, TextureFormat.ARGB32, false);
                     Color32[] pixels = textureFace.GetPixels32();
                     tempTexture.SetPixels32(pixels);
                     tempTexture.Apply();
                     if (png)
                     {
                         File.WriteAllBytes(texturePath, tempTexture.EncodeToPNG());
                     }
                     else
                     {
                         File.WriteAllBytes(texturePath, tempTexture.EncodeToJPG(exportationOptions.DefaultQualityLevel));
                     }
                 }
                 catch (Exception ex)
                 {
                     Debug.LogException(ex);
                 }
                 finally
                 {
                     if (!isReadable) importTool.ForceUpdate();
                 }
             }
         }
     }
 }
예제 #27
0
    void WriteImage()
    {
        if(_splashEnabled == true) {
            try
            {
                tmpUserMap = Kmanager.GetUsersLblTex();
                byte[] bytes = tmpUserMap.EncodeToJPG();
                // Create a file using the FileStream class.
                if (!Directory.Exists(ImageDir))
                    Directory.CreateDirectory(ImageDir);

                FileStream fWrite = new FileStream(ImageFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 8, true);

                // Write the bytes to the file.
                fWrite.Write(bytes, 0, bytes.Length);

                // Close the stream.
                fWrite.Close();
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
            }
        }
    }
예제 #28
0
		public void ConvertToJPG (string originalFile, string newFile, Color background, int quality = 75)
		{
			
			Texture2D png = new Texture2D (1, 1);

			byte[] pngData = System.IO.File.ReadAllBytes (originalFile);
			png.LoadImage (pngData);


			Color[] srcColors = png.GetPixels ();
			Color[] dstColors = new Color[srcColors.Length];
			for (int i = 0; i < srcColors.Length; i++) {
				Color srcColor = srcColors [i];
				float a = srcColor.a;
				if (a == 0.0F) {
					srcColor = background;
					srcColor.a = 1.0F;
				}

				dstColors [i] = new Color (srcColor.r, srcColor.g, srcColor.b, 1.0F);
			}

			Texture2D result = new Texture2D (png.width, png.height, TextureFormat.ARGB32, false);
			result.SetPixels (dstColors);
			result.Apply ();
			png = result;


			byte[] jpgData = png.EncodeToJPG (quality);
			var file = System.IO.File.Open (newFile, System.IO.FileMode.Create);
			var binary = new System.IO.BinaryWriter (file);
			binary.Write (jpgData);
			file.Close ();
			Destroy (png);
			//Resources.UnloadAsset(png);
		}
예제 #29
0
파일: LevelReader.cs 프로젝트: Appms/OniOni
    public void CreateLevelTexture()
    {
        Texture2D levelmap = new Texture2D(ResolutionGrid, ResolutionGrid, TextureFormat.RGB24, false, false);
        levelmap.filterMode = FilterMode.Point;
        Color[] colors = new Color[ResolutionGrid * ResolutionGrid];

        for (int i=0; i<ResolutionGrid; i++){
            for(int j=0; j<ResolutionGrid; j++){
                node newNode = (node)gridNodes[i * ResolutionGrid + j];

                float colorSample = binary ? (newNode.size >= 0 ? 0.0f : 1.0f) : 1f - (float)newNode.size / ResolutionGrid;

                colors[(ResolutionGrid - i - 1) * ResolutionGrid + j] = new Color(colorSample, colorSample, colorSample);
            }
        }

        levelmap.SetPixels(colors);
        levelmap.Apply();

        byte[] bytes = levelmap.EncodeToJPG();

        //File.WriteAllBytes(Application.dataPath + "/Resources/Levelmap.jpg", bytes);
        File.WriteAllBytes(Application.persistentDataPath + "/Levelmap.jpg", bytes);

        levelMap = levelmap;

        Debug.Log("Texture Created!");
    }
예제 #30
0
    public void LateUpdate()
    {
        if (togglingBack) {
            //Debug.Log(toggleBackStartTime + delayAfterShot + ":" + Time.realtimeSinceStartup);
            if (toggleBackStartTime + delayAfterShot > Time.realtimeSinceStartup) {
                return;
            } else {
                ToggleBack();
            }
        }
        if (togglingBack) return;

        if (!takeHiResShot && CrossPlatformInputManager.GetButtonDown("Screenshot") ) {
            TakeHiResShot();
        }

        if (takeHiResShot) {
            if (pauseTime) Time.timeScale = 0;
        }
        if (takeHiResShot) framesWaited++;
        if (takeHiResShot && framesWaited < waitFrames) Debug.Log("Waiting:" + framesWaited + " out of " + waitFrames);
        if (takeHiResShot && framesWaited >= waitFrames) {
            int w = (int) (resWidth*resMult);
            int h = (int) (resHeight*resMult);
            RenderTexture rt = new RenderTexture(w, h, 24);
            targetCamera.targetTexture = rt;
            Texture2D screenShot = new Texture2D(w, h, TextureFormat.RGB24, false);
            targetCamera.Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, w, h), 0, 0);
            targetCamera.targetTexture = null;
            RenderTexture.active = null; // JC: added to avoid errors

        #if UNITY_EDITOR
            if (!Application.isPlaying) {
                DestroyImmediate(rt);
            } else {
                Destroy(rt);
            }

        #else
        Destroy(rt);
        #endif

            byte[] bytes = null;
            switch (imageFormat) {
                case eImageFormat.jpg:
                    bytes = screenShot.EncodeToJPG(jpegQuality);
                    break;
                case eImageFormat.png:
                    bytes = screenShot.EncodeToPNG();
                    break;
            }

            toggleBackStartTime = Time.realtimeSinceStartup;
            togglingBack = true;
            //Invoke("ToggleBack", delayAfterShot);

        #if !UNITY_WEBPLAYER
            string filename = ScreenShotName(resWidth, resHeight);
            System.IO.File.WriteAllBytes(filename, bytes);
            Debug.Log(string.Format("Took screenshot to: {0}", filename));
            takeHiResShot = false;
        #else
            Debug.Log("Saving screenshots is not avaiable in the webplayer.");
        #endif
        }
    }
    // Update is called once per frame
    void Update()
    {
        //Added by Yuqi Ding
        MetaCoreInterop.meta_get_point_cloud(ref _metaPointCloud, _translation, _rotation);

        // obtain the rgb data
        MetaCoreInterop.meta_get_rgb_frame(RawPixelBuffer, _translation_rgb, _new_rotation_rgb);  // The buffer is pre-allocated by constructor.

        // obtain the rgb data parameter
        MetaCoreInterop.meta_get_rgb_intrinsics(ref _camera_params);

        // 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_rgb.Length; ++i)
        {
            isEqual = _rotation_rgb[i] == _new_rotation_rgb[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_rgb.Length; ++i)
            {
                _rotation_rgb[i] = _new_rotation_rgb[i];
            }

            _rgbTexture.LoadRawTextureData(RawPixelBuffer, _totalBufferSize);
            _rgbTexture.Apply();
        }

        SetDepthToWorldTransform();

        if (SavePointCloud && (Time.frameCount % 48 == 0))
        {
            MarshalMetaPointCloud();

            int num = _metaPointCloud.num_points;
            if (num != 0)
            {
                //save the point cloud
                string PointCloudName = string.Format("{0}/{1:D04} shot.ply", folder, Time.frameCount);
                SavePointCloudToPly(PointCloudName, _pointCloud);
                string PointCloudIntrName = string.Format("{0}/{1:D04} pointcloud_Intr.txt", folder, Time.frameCount);
                SavePointCloudPara(PointCloudIntrName, _translation, _rotation);

                //save the rgb frame
                Color[] color2dtemp = _rgbTexture.GetPixels();
                for (int i = 0; i < color2dtemp.Length; i++)
                {
                    float temp = 0.0f;
                    temp             = color2dtemp[i].r;
                    color2dtemp[i].r = color2dtemp[i].b;
                    color2dtemp[i].b = temp;
                }
                _rgbTexture.SetPixels(color2dtemp);
                //Debug.Log("Swap r and b");

                byte[] bytes   = _rgbTexture.EncodeToJPG();
                string rgbName = string.Format("{0}/{1:D04} shot.jpg", folder, Time.frameCount);
                File.WriteAllBytes(rgbName, bytes);
                string rgbIntrName = string.Format("{0}/{1:D04} shot_Intr.txt", folder, Time.frameCount);
                SaveRGBIntrinsics(rgbIntrName, _camera_params);
                string rgbParaName = string.Format("{0}/{1:D04} shot_Para.txt", folder, Time.frameCount);
                SaveRGBPara(rgbParaName, _translation_rgb, _rotation_rgb);
            }
            // Added end
        }
    }
예제 #32
0
        private void CopyTextureCube(string texturePath, Cubemap cubemap, BabylonTexture babylonTexture, bool hdr = false)
        {
            if (!babylonScene.AddTextureCube(texturePath))
            {
                return;
            }
            ExporterWindow.ReportProgress(1, "Parsing texture cube: " + texturePath);
            var srcTexturePath = AssetDatabase.GetAssetPath(cubemap);
            bool textureNotExistsMode = (SceneController != null && SceneController.skyboxOptions.textureFile == BabylonTextureExport.IfNotExists);
            bool png = (exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG);
            string fext = (png == true) ? ".png" : ".jpg";
            try
            {
                if (hdr)
                {
                    var hdrTexturePath = Path.Combine(babylonScene.OutputPath, Path.GetFileName(texturePath));
                    bool writeHdrTexture = true;
                    string textureHdrName = Path.GetFileName(hdrTexturePath);
                    if (textureNotExistsMode && File.Exists(hdrTexturePath))
                    {
                        writeHdrTexture = false;
                        ExporterWindow.ReportProgress(1, "Texture hdr cube item exists: " + textureHdrName);
                    }
                    if (writeHdrTexture)
                    {
                        ExporterWindow.ReportProgress(1, "Copying hdr texture cube item: " + textureHdrName);
                        File.Copy(srcTexturePath, hdrTexturePath, true);
                    }
                }
                else
                {
                    var importTool = new BabylonTextureImporter(srcTexturePath);
                    bool isReadable = importTool.IsReadable();
                    if (!isReadable) importTool.SetReadable();
                    try
                    {
                        foreach (CubemapFace face in Enum.GetValues(typeof(CubemapFace)))
                        {
                            var faceTexturePath = Path.Combine(babylonScene.OutputPath, Path.GetFileNameWithoutExtension(texturePath));
                            switch (face)
                            {
                                case CubemapFace.PositiveX:
                                    faceTexturePath += ("_px" + fext);
                                    break;
                                case CubemapFace.NegativeX:
                                    faceTexturePath += ("_nx" + fext);
                                    break;
                                case CubemapFace.PositiveY:
                                    faceTexturePath += ("_py" + fext);
                                    break;
                                case CubemapFace.NegativeY:
                                    faceTexturePath += ("_ny" + fext);
                                    break;
                                case CubemapFace.PositiveZ:
                                    faceTexturePath += ("_pz" + fext);
                                    break;
                                case CubemapFace.NegativeZ:
                                    faceTexturePath += ("_nz" + fext);
                                    break;
                                default:
                                    continue;
                            }
                            bool writeFaceTexture = true;
                            string textureFaceName = Path.GetFileName(faceTexturePath);
                            if (textureNotExistsMode && File.Exists(faceTexturePath))
                            {
                                writeFaceTexture = false;
                                ExporterWindow.ReportProgress(1, "Texture cube item exists: " + textureFaceName);
                            }
                            if (writeFaceTexture)
                            {
                                ExporterWindow.ReportProgress(1, "Exporting texture cube item: " + textureFaceName);
                                var tempTexture = new Texture2D(cubemap.width, cubemap.height, TextureFormat.ARGB32, false);

                                Color[] pixels = cubemap.GetPixels(face);
                                tempTexture.SetPixels(pixels);
                                tempTexture.Apply();

                                // Flip faces in cube texture.
                                tempTexture = FlipTexture(tempTexture);

                                // Encode cube face texture
                                if (png)
                                {
                                    File.WriteAllBytes(faceTexturePath, tempTexture.EncodeToPNG());
                                }
                                else
                                {
                                    File.WriteAllBytes(faceTexturePath, tempTexture.EncodeToJPG(exportationOptions.DefaultQualityLevel));
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (!isReadable) importTool.ForceUpdate();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
            }
            if (babylonTexture != null)
            {
                var textureName = Path.GetFileNameWithoutExtension(texturePath);
                if (hdr) textureName += ".hdr";
                babylonTexture.name = textureName;
                babylonTexture.isCube = true;
                babylonTexture.level = exportationOptions.ReflectionDefaultLevel;
                babylonTexture.coordinatesMode = 3;
            }
        }
예제 #33
0
    /// <summary>
    /// Save unity cubemap into NPOT 6x1 cubemap/texture atlas in the following format PX NX PY NY PZ NZ
    /// </summary>
    /// <description>
    /// Supported format: PNG/JPG
    /// Default file name: using current time OVR_hh_mm_ss.png 
    /// </description>
    public static bool SaveCubemapCapture(Cubemap cubemap, string pathName = null)
    {
        string fileName;
        string dirName;
        int width = cubemap.width;
        int height = cubemap.height;
        int x = 0;
        int y = 0;
        bool saveToPNG = true;

        if (string.IsNullOrEmpty(pathName))
        {
            dirName = Application.persistentDataPath + "/OVR_ScreenShot360/";
            fileName = null;
        }
        else
        {
            dirName = Path.GetDirectoryName(pathName);
            fileName = Path.GetFileName(pathName);

            if (dirName[dirName.Length - 1] != '/' || dirName[dirName.Length - 1] != '\\')
                dirName += "/";
        }

        if (string.IsNullOrEmpty(fileName))
            fileName = "OVR_" + System.DateTime.Now.ToString("hh_mm_ss") + ".png";

        string extName = Path.GetExtension(fileName);
        if (extName == ".png")
        {
            saveToPNG = true;
        }
        else if (extName == ".jpg")
        {
            saveToPNG = false;
        }
        else
        {
            Debug.LogError("Unsupported file format" + extName);
            return false;
        }

        // Validate path
        DirectoryInfo dirInfo;
        try
        {
            dirInfo = System.IO.Directory.CreateDirectory(dirName);
        }
        catch (System.Exception e)
        {
            Debug.LogError("Failed to create path " + dirName + " since " + e.ToString());
            return false;
        }

        // Create the new texture
        Texture2D tex = new Texture2D(width * 6, height, TextureFormat.RGB24, false);
        if (tex == null)
        {
            Debug.LogError("[OVRScreenshotWizard] Failed creating the texture!");
            return false;
        }

        // Merge all the cubemap faces into the texture
        // Reference cubemap format: http://docs.unity3d.com/Manual/class-Cubemap.html
        CubemapFace[] faces = new CubemapFace[] { CubemapFace.PositiveX, CubemapFace.NegativeX, CubemapFace.PositiveY, CubemapFace.NegativeY, CubemapFace.PositiveZ, CubemapFace.NegativeZ };
        for (int i = 0; i < faces.Length; i++)
        {
            // get the pixels from the cubemap
            Color[] srcPixels = null;
            Color[] pixels = cubemap.GetPixels(faces[i]);
            // if desired, flip them as they are ordered left to right, bottom to top
            srcPixels = new Color[pixels.Length];
            for (int y1 = 0; y1 < height; y1++)
            {
                for (int x1 = 0; x1 < width; x1++)
                {
                    srcPixels[y1 * width + x1] = pixels[((height - 1 - y1) * width) + x1];
                }
            }
            // Copy them to the dest texture
            tex.SetPixels(x, y, width, height, srcPixels);
            x += width;
        }

        try
        {
            // Encode the texture and save it to disk
            byte[] bytes = saveToPNG ? tex.EncodeToPNG() : tex.EncodeToJPG();

            System.IO.File.WriteAllBytes(dirName + fileName, bytes);
            Debug.Log("Cubemap file created " + dirName + fileName);
        }
        catch (System.Exception e)
        {
            Debug.LogError("Failed to save cubemap file since " + e.ToString());
            return false;
        }

        DestroyImmediate(tex);
        return true;
    }
예제 #34
0
		public void ConvertToJPG (string originalFile, string newFile, int quality = 75)
		{
			Texture2D png = new Texture2D (1, 1);

			byte[] pngData = System.IO.File.ReadAllBytes (originalFile);
			png.LoadImage (pngData);
			byte[] jpgData = png.EncodeToJPG (quality);
			var file = System.IO.File.Open (newFile, System.IO.FileMode.Create);
			var binary = new System.IO.BinaryWriter (file);
			binary.Write (jpgData);
			file.Close ();
			Destroy (png);
			//Resources.UnloadAsset(png);
		}
예제 #35
0
		private static byte[] GetImageBytesFromTexture(string imageFileName, Texture2D imageTexture)
		{
			string[] fileNameComponents = imageFileName.Split ('.');
			if (fileNameComponents.Length < 2)
			{
				SoomlaUtils.LogError(TAG, "(GetImageBytesFromTexture) image file without extension: " + imageFileName);
				return null;
			}

			string fileExtension = fileNameComponents [1];
			if (fileExtension == "png")
				return imageTexture.EncodeToPNG();
			else
				return imageTexture.EncodeToJPG();
		}
예제 #36
0
 private void WriteTextureFile(string filename, Texture2D texture, bool png)
 {
     if (png)
     {
         File.WriteAllBytes(filename, texture.EncodeToPNG());
     }
     else
     {
         File.WriteAllBytes(filename, texture.EncodeToJPG(ExporterWindow.exportationOptions.DefaultQualityLevel));
     }
 }