十年網站開發(fā)經驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網站問題一站解決
小編這次要給大家分享的是Unity如何實現圖片生成灰白圖,文章內容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
成都創(chuàng)新互聯公司從2013年創(chuàng)立,先為壽寧等服務建站,壽寧等地企業(yè),進行企業(yè)商務咨詢服務。為壽寧企業(yè)網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。
效果
原圖

生成出來的灰白圖

制作方法
把文章末尾的的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(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如何實現圖片生成灰白圖的文章,如果覺得文章內容寫得不錯的話,可以把它分享出去給更多人看到。