Search code examples
unity-game-enginetexturestexture2d

Texture from Assets folder to Texture2D and the save?


I have a Texture in the Assets folder with (Texture Type = Advanced, Read/Write Enabled = true, Max Size = 512, Format = RGB 24 bit). Now I want to read this texture and then copy the pixels into another texture2d and save that.

private Texture2D sourceImg;

...

Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
tex.SetPixels(sourceImg.GetPixels(0,0,512,512));
tex.Apply();
byte[] png = tex.EncodeToPNG();
File.WriteAllBytes(Application.persistentDataPath + "/Screenshot.png", png);

I don't know, why this simple code is not working?

When I add the new tex to a quad with:

quad.renderer.material.mainTexture = tex;

It works.


Solution

  • OK, I solved it. Just do this: Go to Edit -> Project Settings -> Player -> Other Settings and change Write Access to External.