本文主要是介绍Unity中生成图片的灰白图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
效果
原图
生成出来的灰白图
制作方法
把文章末尾的的TextureUtils.cs脚本放到工程的Assets / Editor目录中
然后选中项目中的一张图片,然后点击菜单Tools / GenGrayTexture
就会在同级目录中生成灰白图片了
// TextureUtils.csusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;public class TextureUtils : MonoBehaviour
{[MenuItem("Tools/GenGrayTexture")]public static void GenGrayTexture(){// 获取选中的图片var textures = Selection.GetFiltered<Texture2D>(SelectionMode.DeepAssets);foreach (var t in textures){var path = AssetDatabase.GetAssetPath(t);// 如果提示图片不可读,需要设置一下isReadable为true, 操作完记得再设置为falsevar imp = AssetImporter.GetAtPath(path) as TextureImporter;imp.isReadable = true;AssetDatabase.ImportAsset(path);var newTexture = new Texture2D(t.width, t.height, TextureFormat.RGBA32, false);var colors = t.GetPixels();var targetColors = newTexture.GetPixels();for (int i = 0, len = colors.Length; i < len; ++i){var c = colors[i];// 颜色值计算,rgb去平均值var v = (c.r + c.g + c.b) / 3f;targetColors[i] = new Color(v, v, v, c.a);}newTexture.SetPixels(targetColors);string fname = path.Split('.')[0] + "_gray.png";File.WriteAllBytes(fname, newTexture.EncodeToPNG());imp.isReadable = false;AssetDatabase.Refresh();}}
}
如果要批量修改,可以用Directory.GetFiles接口来获取特定格式的文件
var files = Directory.GetFiles("D:\\path", "*.*", SearchOption.AllDirectories);
foreach(var f in files)
{if(!f.EndsWith(".png") && !f.EndsWith(".jpg")) continue;// TODO...}
这篇关于Unity中生成图片的灰白图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!