The method of generating gray and white image from pictures by unity

Time:2020-11-21

In this paper, we share the specific code of unity to generate gray and white image for your reference. The specific content is as follows

effect

Original picture

The gray and white map is generated

Production method

Put the end of the article TextureUtils.cs Project scriptAssets / EditorIn the table of contents

Then select an image in the project and click on the menuTools / GenGrayTexture

A gray image will be generated in the peer directory

// 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()
 {
  //Get the selected picture
  var textures = Selection.GetFiltered<Texture2D>(SelectionMode.DeepAssets);
  foreach (var t in textures)
  {
   var path = AssetDatabase.GetAssetPath(t);

   //If the prompt image is unreadable, you need to set isreadable to true, and remember to set it to false after the operation
   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];
    //Color value calculation, RGB average value
    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();
  }
 }
}

If you want to modify in batch, you can use Directory.GetFiles Interface to get a file in a specific format


var files = Directory.GetFiles("D:\path", "*.*", SearchOption.AllDirectories);
foreach(var f in files)
{
 if(!f.EndsWith(".png") && !f.EndsWith(".jpg")) continue;
 // TODO...
 
}

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.