Unity一鍵重命名文件夾下所有圖片(自帶翻譯)

//=====================================================
// - FileName:      RenamePic.cs
// - Author:       #AuthorName#
// - CreateTime:    #CreateTime#
// - Email:         #AuthorEmail#
// - Description:   
// -  (C) Copyright 2019, Autumn.
// -  All Rights Reserved.
//======================================================
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Qarth;
using Object = UnityEngine.Object;
using System.Security.Cryptography;
using System.Text;
using System.Net;

namespace GameWish.Game
{
    public static class RenamePic
    {
        static int fileSumCount = 0;
        static int progress = 0;
        static string info = string.Empty;

        [MenuItem("Assets/RenamePic(選中文件夾即可重命名文件夾下所有圖片)")]
        static void RenameFolderPic()
        {
            List<string> lstPaths = new List<string>();
            List<DirectoryInfo> lstDir = new List<DirectoryInfo>();

            if (Selection.assetGUIDs != null)
            {
                for (int i = 0; i < Selection.assetGUIDs.Length; i++)
                {
                    DirectoryInfo direction = new DirectoryInfo(AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[i]));
                    lstPaths.Add(AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[i]));
                    lstDir.Add(direction);
                }
            }
            if (lstDir == null)
            {
                Log.e("未選中文件夾!");
                return;
            }

            //初始化總文件數
            fileSumCount = 0;
            progress = 0;
            info = string.Empty;

            int index = 1;
            List<string> lstName = new List<string>();

            for (int i = 0; i < lstDir.Count; i++)
            {
                FileInfo[] files = lstDir[i].GetFiles("*", SearchOption.AllDirectories);
                // fileSumCount += files.Length;

                if (files != null)
                {
                    for (int j = 0; j < files.Length; j++)
                    {
                        lstName.Add(files[j].Name);
                    }
                }

            }
            //RunProgressBar();

            for (int i = 0; i < lstDir.Count; i++)
            {
                FileInfo[] files = lstDir[i].GetFiles("*", SearchOption.AllDirectories);
                if (files != null)
                {
                    for (int j = 0; j < files.Length; j++)
                    {
                        progress++;
                        //進度顯示
                        ShowProgress((j + 1) / files.Length, files.Length, j + 1, files[j].Name);
                        if (files[j].Name.EndsWith(".png") || files[j].Name.EndsWith(".jpg")) //重命名圖片
                        {
                            if (files[j].Name.Contains(lstDir[i].Name))
                            {
                                Log.e("{0} 已經重命名過!", files[j].Name);
                            }
                            else
                            {
                                string path = string.Format("{0}/{1}", lstPaths[i], files[j].Name);
                                string fileName = files[j].Name.Replace(".jpg", "").Replace(".png", "").Replace(" ", "");
                                if (CheckString(fileName))
                                {
                                    fileName = GetTranslationFromBaiduFanyi(appId, fileName, Language.zh, Language.en).Replace(" ", "");
                                    Log.e(fileName);
                                }
                                string newName = string.Format("{0}_{1}", lstDir[i].Name, fileName);

                                if (!CheckName(newName, lstName, () =>
                                {
                                    index++;
                                    newName = string.Format("{0}_{1}", lstDir[i].Name, fileName);
                                },
                                () => { lstName.Add(newName); }))
                                {
                                    CheckName(newName, lstName, () =>
                                    {
                                        index++;
                                        newName = string.Format("{0}_{1}", lstDir[i].Name, fileName);
                                    }, () => { lstName.Add(newName); });
                                }

                                AssetDatabase.RenameAsset(path, newName);
                                Log.i("{0} Rename Success!", files[j].Name);
                            }
                        }
                    }
                }
            }
            EditorUtility.ClearProgressBar();
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
        static bool CheckName(string name, List<string> lstName, Action yes, Action no)
        {
            if (lstName == null) { return false; }
            if (lstName.Contains(name))
            {
                if (yes != null)
                {
                    yes();
                }
                return true;
            }
            else
            {
                if (no != null)
                {
                    no();
                }
                return false;
            }
        }

        static string[] m_chaos = new string[] {
            ".jpg", ".png",  " ",
            "-", "*", "!", "@", "#", "$", "%", "^", "&", "(", ")", "+", "=", "|",
            ";", "<", ">", "?", "/", ":", "{", "}", "[", "]", "_","》","《",",","、"
        };

        static string RemoveChaosLetter(this string name)
        {
            for (int i = 0; i < m_chaos.Length; i++)
            {
                name = name.Replace(m_chaos[i], "");
            }
            return name;
        }
        public static void ShowProgress(float val, int total, int cur, string picname)
        {
            EditorUtility.DisplayProgressBar(string.Format("Rename {0} ing...", picname), string.Format("wait({0}/{1}) ", cur, total), val);
        }

        // 判斷 當前字符是否爲中文
        private static bool IsChinese(char c)
        {
            return c >= 0x4E00 && c <= 0x9FA5;
        }

        public static bool CheckString(string str)
        {
            char[] ch = str.ToCharArray();
            if (str != null)
            {
                for (int i = 0; i < ch.Length; i++)
                {
                    if (IsChinese(ch[i]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private static string appId = "20191126000360543";
        private static string password = "TJv1Z17G5cUtfRUtQrJK";
        private static string GetTranslationFromBaiduFanyi(string id, string q, Language from, Language to, string language = "英文")
        {

            string jsonResult = String.Empty;
            //源語言
            string languageFrom = from.ToString().ToLower();
            //目標語言
            string languageTo = to.ToString().ToLower();
            //隨機數
            string randomNum = System.DateTime.Now.Millisecond.ToString();
            //md5加密
            string md5Sign = GetMD5WithString(appId + q + randomNum + password);
            //url
            string url = String.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}",
                q,
                languageFrom,
                languageTo,
                appId,
                randomNum,
                md5Sign
                );
            WebClient wc = new WebClient();
            try
            {
                jsonResult = wc.DownloadString(url);
            }
            catch
            {
                jsonResult = string.Empty;
            }
            //結果轉json
            TranslationResult temp = LitJson.JsonMapper.ToObject<TranslationResult>(jsonResult);
            string tar = "";
            if (null != temp)
            {
                if (string.IsNullOrEmpty(language))
                {
                    for (int i = 0; i < temp.trans_result.Length; i++)
                    {
                        string str = @"{""Key"":" + id + @",""Content"":" + @"""" + temp.trans_result[i].dst + @"""" + "},";
                    }
                }
                else
                {
                    for (int i = 0; i < temp.trans_result.Length; i++)
                    {
                        string str = language + "|" + temp.trans_result[i].dst;
                        Log.e("Translation Results{0}", str);
                        tar = temp.trans_result[i].dst;
                    }
                }
            }
            return tar;
        }

        private static string GetMD5WithString(string input)
        {
            if (input == null)
            {
                return null;
            }
            MD5 md5Hash = MD5.Create();
            //將輸入字符串轉換爲字節數組並計算哈希數據  
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            //創建一個 Stringbuilder 來收集字節並創建字符串  
            StringBuilder sBuilder = new StringBuilder();
            //循環遍歷哈希數據的每一個字節並格式化爲十六進制字符串  
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            //返回十六進制字符串  
            return sBuilder.ToString();
        }
    }
    public class Translation
    {
        public string src { get; set; }
        public string dst { get; set; }
    }

    public enum Language
    {
        //百度翻譯API官網提供了多種語言,這裏只列了幾種
        zh,
        en,
        spa,
        fra,
        th,
        ara,
        ru,
        pt,
        de,
        el,
        vie,
        cht,
        yue,
    }

    public class TranslationResult
    {
        //錯誤碼,翻譯結果無法正常返回
        public string Error_code { get; set; }
        public string Error_msg { get; set; }
        public string from { get; set; }
        public string to { get; set; }
        public string Query { get; set; }
        //翻譯正確,返回的結果
        //這裏是數組的原因是百度翻譯支持多個單詞或多段文本的翻譯,在發送的字段q中用換行符(\n)分隔
        public Translation[] trans_result { get; set; }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章