本文实例为大家分享了unity生成图片灰白图的具体代码,供大家参考,具体内容如下
效果
原图
生成出来的灰白图
制作方法
把文章末尾的的textureutils.cs脚本放到工程的assets / editor目录中
然后选中项目中的一张图片,然后点击菜单tools / gengraytexture
就会在同级目录中生成灰白图片了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
// 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接口来获取特定格式的文件
1
2
3
4
5
6
7
|
var files = directory.getfiles( "d:\\path" , "*.*" , searchoption.alldirectories); foreach( var f in files) { if (!f.endswith( ".png" ) && !f.endswith( ".jpg" )) continue ; // todo... } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/linxinfa/article/details/88553932