小编这次要给大家分享的是Unity如何实现图片生成灰白图,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。
效果
原图
生成出来的灰白图
制作方法
把文章末尾的的TextureUtils.cs脚本放到工程的Assets / Editor目录中
然后选中项目中的一张图片,然后点击菜单Tools / GenGrayTexture
就会在同级目录中生成灰白图片了
// TextureUtils.cs
using 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, 操作完记得再设置为false
var 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如何实现图片生成灰白图的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。