Unity 提取像素图

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class Test : MonoBehaviour
{
    
    public int m_x;
    public int m_y;



    IEnumerator enumerator()
    {
        int a = 0;
        Texture2D[] temp = Resources.LoadAll<Texture2D>("Imgs");
        foreach (Texture2D tx in temp)
        {
            Texture2D texture = new Texture2D(15, 15);
            int w = tx.width;
            int h = tx.height;
            float x = w / m_x;
            float y = h / m_y;
            float startx = x / 2;
            float starty = y / 2;
            Color color;
            for (int i =0;i<m_x;i++)
            {
                for (int j=0;j<m_y; j++)
                {
                    color = tx.GetPixel((int)(startx +x*i), (int)(starty + y * j));
                    texture.SetPixel(i, j, color);
                }
            }
            ToPng(texture,
        Application.dataPath + "/temp",a.ToString ("000"));
            yield return 1;
            a++;
        }
    }

    void Start()
    {
        StartCoroutine(enumerator());
    }

    void ToPng(Texture2D texture, string contents, string pngName)
    {
        if (!Directory.Exists(contents))
            Directory.CreateDirectory(contents);
        var temp = texture.EncodeToPNG();
        FileStream file = File.Open(contents + "/" + pngName + ".png", FileMode.Create);
        BinaryWriter writer = new BinaryWriter(file);
        writer.Write(temp);
        file.Close();
    }

}

 

posted @ 2022-02-18 12:45  法小鱿  阅读(209)  评论(0编辑  收藏  举报