Skip to content

Instantly share code, notes, and snippets.

@openroomxyz
Created April 21, 2020 13:50
Show Gist options
  • Save openroomxyz/23faf8b0c22ff557169f0d4fa430674f to your computer and use it in GitHub Desktop.
Save openroomxyz/23faf8b0c22ff557169f0d4fa430674f to your computer and use it in GitHub Desktop.
Unity Editor : How to create in code Texture2D and save as file an PNG image lunch from menu?
sing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEditor;
public class CreatingPNG : MonoBehaviour
{
public static Texture2D CreateTexture()
{
int width = 100;
int height = 100;
Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false);
texture.filterMode = FilterMode.Point;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
float r = (float)((float)i / width);
if(j > i)
{
texture.SetPixel(j, height - 1 - i, new Color(r, r, r, 1.0f));
}
else
{
texture.SetPixel(j, height - 1 - i, new Color(r, r, r, 0.2f));
}
}
}
texture.Apply();
return texture;
}
Texture2D SaveTexture(Texture2D texture, string filePath)
{
byte[] bytes = texture.EncodeToPNG();
FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter writer = new BinaryWriter(stream);
for (int i = 0; i < bytes.Length; i++)
{
writer.Write(bytes[i]);
}
writer.Close();
stream.Close();
DestroyImmediate(texture);
//I can't figure out how to import the newly created .png file as a texture
AssetDatabase.Refresh();
Texture2D newTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(filePath, typeof(Texture2D));
if (newTexture == null)
{
Debug.Log("Couldn't Import");
}
else
{
Debug.Log("Import Successful");
}
return newTexture;
}
[MenuItem("Examples/Save Texture to file")]
static void Apply()
{
Texture2D texture = CreateTexture();
texture.name = "lol.png";
var path = EditorUtility.SaveFilePanel(
"Save texture as PNG",
"",
texture.name + ".png",
"png");
if (path.Length != 0)
{
var pngData = texture.EncodeToPNG();
if (pngData != null)
File.WriteAllBytes(path, pngData);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment