Skip to content

Instantly share code, notes, and snippets.

@supertask
Created November 10, 2023 18:46
Show Gist options
  • Save supertask/21e72cb2ae01d175abdc5bf421dc4a57 to your computer and use it in GitHub Desktop.
Save supertask/21e72cb2ae01d175abdc5bf421dc4a57 to your computer and use it in GitHub Desktop.
Texture2DPNGExporter for MetaTex
using UnityEngine;
using UnityEditor;
using System.IO;
public class Texture2DPNGExporter : MonoBehaviour
{
[MenuItem("Assets/Export Selected Textures to PNG")]
public static void SaveTexturesToPNG()
{
foreach (Object selectedObject in Selection.objects)
{
Texture2D texture = selectedObject as Texture2D;
if (texture != null)
{
string filePath = EditorUtility.SaveFilePanel("Save Texture as PNG", "", texture.name + ".png", "png");
if (string.IsNullOrEmpty(filePath))
{
Debug.LogError("File path is empty for texture: " + texture.name);
continue;
}
SaveTextureToPNG(texture, filePath);
}
}
}
private static void SaveTextureToPNG(Texture2D texture, string filePath)
{
RenderTexture renderTex = RenderTexture.GetTemporary(
texture.width,
texture.height,
0,
RenderTextureFormat.Default,
RenderTextureReadWrite.Linear);
Graphics.Blit(texture, renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Texture2D newTexture = new Texture2D(texture.width, texture.height);
newTexture.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
newTexture.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(renderTex);
byte[] pngData = newTexture.EncodeToPNG();
if (pngData != null)
{
File.WriteAllBytes(filePath, pngData);
Debug.Log("Texture saved as PNG: " + filePath);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment