[编辑器]Unity批量处理图片
加载图片,将其画在一张RenderTexture中,再新建一张Texture2D,从rt中读出来处理过的数据,再存进原路径中,
比如要将所有图片扩大1.5倍:
public static void ChangeSize(params string[] paths) { var texture2Ds = AssetDatabase.FindAssets ("t:Texture2D", paths); var retTexture = new Texture2D (1, 1, TextureFormat.ARGB32, false); int count = textures.Length; for(int i = 0; i < count; ++i) { var path = AssetDatabase.GUIDToAssetPath (textures[i]); var texture = AssetDatabase.LoadAssetAtPath<Texture2D> (path); var rt = RenderTexture.GetTemporary ((int)(texture.width * 1.5f), (int)(texture.height * 1.5f), 0, RenderTextureFormat.ARGB32); texture.DiscardContents (); Graphics.Blit (texture, rt); RenderTexture.active = texture; retTexture.Resize (rt.width, rt.height); retTexture.ReadPixels (new Rect (0, 0, rt.width, rt.height), 0, 0); retTexture.Apply (); File.WriteAllBytes (path, retTexture.EncodeToPNG ()); RenderTexture.ReleaseTemporary (rt); } AssetDatabase.SaveAssets (); AssetDatabase.Refresh (); }
为防止重复编辑,可以在userdata中添加标志:
var im = AssetImporter.GetAtPath (path); if (im.userData.Contains ("R2;")) continue; im.userData += "R2;";