Question by
kenmarold · May 30, 2017 at 05:42 PM ·
c#texture2dencodetopng
Unity EncodeToPNG saving at 512x512, can't change dimension
I can't seem to get EncodeToPNG() to save to a file dimension other than 512 x 512 even though my texture is 1280 x 1024 which I'm pulling from the dimensions of my RenderTexture object 'tex'. What am I missing? What am I missing? Thank you!
// Saves texture as PNG file.
using UnityEngine;
using System.Collections;
using System.IO;
public class SaveTexture : MonoBehaviour {
public RenderTexture tex;
int tWidth, tHeight;
int getTextureWidth(int texWidth)
{
return tex.width;
}
int getTextureHeight(int texHeight)
{
return tex.height;
}
public void Start()
{
tWidth = getTextureWidth(tex.width);
tHeight = getTextureHeight(tex.height);
Debug.Log("Texture Width: " + tWidth + ", Texture Height: " + tHeight);
}
Texture2D toTexture2D(RenderTexture rTex)
{
Texture2D tex = new Texture2D(tWidth, tHeight, TextureFormat.ARGB32, false);
RenderTexture.active = rTex;
tex.ReadPixels(new Rect(0, 0, tWidth, tHeight), 0, 0);
tex.Apply();
return tex;
}
// Save Texture as PNG
public void SaveTexturePNG()
{
Texture2D myTexture = tex.toTexture2D();
// Encode texture into PNG
byte[] bytes = myTexture.EncodeToPNG();
Object.Destroy(myTexture);
// For testing purposes, also write to a file in the project folder
File.WriteAllBytes(Application.dataPath + "/../AnimalTexture/AnimalTexture.png", bytes);
}
}
Comment