当前位置: 移动技术网 > IT编程>开发语言>c# > Unity实现图片生成灰白图的方法

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

2020年06月23日  | 移动技术网IT编程  | 我要评论

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网