I am using a Perlin noise based map generator for my game and I found a texture that I would like to export is as a PNG to make some more refined edits. If you were wondering why I am not using the one you see, it’s because I need a very precise image, down to the pixel. Bellow you can find my code and thanks in advance:
using UnityEngine;
using System.Collections;
public static class TextureGenerator {
public static Texture2D TextureFromColourMap(Color[] colourMap, int width, int height) {
Texture2D texture = new Texture2D (width, height);
texture.filterMode = FilterMode.Point;
texture.wrapMode = TextureWrapMode.Clamp;
texture.SetPixels (colourMap);
texture.Apply ();
return texture;
}
public static Texture2D TextureFromHeightMap(float[,] heightMap) {
int width = heightMap.GetLength (0);
int height = heightMap.GetLength (1);
Color[] colourMap = new Color[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
colourMap [y * width + x] = Color.Lerp (Color.black, Color.white, heightMap [x, y]);
}
}
return TextureFromColourMap (colourMap, width, height);
}
Texture2D.EncodeToPNG will convert the texture into PNG data and returns an array of bytes. You can then use File.WriteAllBytes to save the byte array to a file.
beacuse you want to save a PNG format, first, check if your texture has transparancy or not, because texture have many different format , for your case, try this code
//first Make sure you're using RGB24 as your texture format
Texture2D texture = new Texture2D(width, height, TextureFormat.RGB24, false);
//then Save To Disk as PNG
byte[] bytes = texture.EncodeToPNG();
var dirPath = Application.dataPath + "/../SaveImages/";
if(!Directory.Exists(dirPath)) {
Directory.CreateDirectory(dirPath);
}
File.WriteAllBytes(dirPath + "Image" + ".png", bytes);
Not to necro a post but this code works like a treat but I was wondering if there is a way to increase the size of the PNG that is output say 250x250 and can you make it transparent.