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;
// 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, ).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)
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} ", picname), string.Format("wait({0}/{1}) ", cur, total), val); }
// 判断当前字符是否为中⽂
random翻译
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("api.fanyi.baidu/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 < ans_result.Length; i++)
{
string str = @"{""Key"":" + id + @",""Content"":" + @"""" + ans_result[i].dst + @"""" + "},";
}
}
else
{
for (int i = 0; i < ans_result.Length; i++)
{
string str = language + "|" + ans_result[i].dst;
Log.e("Translation Results{0}", str);
tar = ans_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; }
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论