欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

Unity实现图片生成灰白图的方法

时间:2021-10-04 08:15:36|栏目:.NET代码|点击:

本文实例为大家分享了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...
 
}

上一篇:C#学习笔记整理_浅谈Math类的方法

栏    目:.NET代码

下一篇:浅谈C#指针问题

本文标题:Unity实现图片生成灰白图的方法

本文地址:http://www.codeinn.net/misctech/178640.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有