I’m trying to make a program that clips png files into 64x64 pixel slices and saves the slices as separate png files.
When I use texture2D.GetPixels() I don’t receive any errors. I then create a new texture2d and use .SetPixels(), and again no errors. I then convert the second texture2D to binary, encode to png, and save with no errors. The file that is created, however, is always completely blank.
All my initial textures are RGBA32 with Read/Write enabled.
Here is my code:
public void ClipTexture(string textureName){
//here is where the exported files will be stored
string pathToExportedFiles = Application.dataPath + "/Exported Graphics/Terrain/"+textureName+"/";
//make sure the needed folders exist
if (!Directory.Exists (pathToExportedFiles)) {
Directory.CreateDirectory(pathToExportedFiles);
}
//get the 2d Texture from the canvas
Texture2D textureToClip = (Texture2D)GameObject.FindGameObjectWithTag ("Canvas").GetComponent<Renderer> ().material.mainTexture;
Debug.Log ("Is TextureToClip null?: " + textureToClip);
//create the file where we will export
FileStream file = File.Open(pathToExportedFiles+"test.png", FileMode.Create);
//convert the texture2d into a smaller 64x64 area
Color[] pixels = textureToClip.GetPixels(0, 0, 64, 64); //x, y, width, height
Texture2D exportThis = new Texture2D (64, 64, TextureFormat.RGBA32, false);
exportThis.SetPixels (pixels);
exportThis.Apply ();
//convert the new texture into bytes
var bytes = exportThis.EncodeToPNG();
//write the new bytes
BinaryWriter binary= new BinaryWriter(file);
binary.Write(bytes);
//finish
file.Close();
}