Search Unity

  1. How can our website serve you better? Give us your feedback. Take our survey and let us know.
    Dismiss Notice

How to EncodeToPng compressed Textures in Unity

Discussion in 'Scripting' started by swifter14, Jul 13, 2018.

  1. swifter14

    swifter14

    Joined:
    Mar 2, 2017
    Posts:
    129
    I develop an app that saves textures (screenshots) and I need to compress them, but then- I can't use `EncodeToPNG` method in order to show the image on the screen.

    My steps:

    Code (CSharp):
    1. Texture2D tex = new Texture2D(recwidth, recheight,TextureFormat.RGB24, false);//RGB24- Because of the next step:
    2. tex.ReadPixels(rex, rdPXX, rdPXY);
    3. tex.Apply();
    4. tex.Compress(false);
    Later I need to show it on the screen with-

    4.
    Code (CSharp):
    1. var bytes = tex.EncodeToPNG();
    But I can't because as we all know `EncodeToPNG` doesn't support compressed textures, so what can I do? It takes a lot of space on my mobile
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,447
    Well, you could:
    - encode it to PNG before you compress it and keep it in memory until you need it.
    - draw the compressed texture to an uncompressed target and then encode that to PNG.

    My main question is really why you would need to encode a texture to PNG in order to show it on the screen.
     
  3. swifter14

    swifter14

    Joined:
    Mar 2, 2017
    Posts:
    129
    Because I need to save it to a file later. But even if I don't use EncodeToPng, I can't use Readpixels with compressed textures ("unsupported texture format - needs to be ARGB32, RGBA32, RGB24"). I don't understand how I can take a screenshot but save it as a compressed texture (also without using Compress because it doesn't work on ios)
     
  4. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,447
    I use this piece of code as extension (of RenderTexture) to be able to make sure the format is ARGB32:
    Code (csharp):
    1.  
    2. /// <summary>
    3. /// Converts this RenderTexture to a RenderTexture in ARGB32 format.
    4. /// Can also return the original RenderTexture if it's already in ARGB32 format.
    5. /// Note that the resulting temporary RenderTexture should be released if no longer used to prevent a memory leak.
    6. /// </summary>
    7. public static RenderTexture ConvertToARGB32(this RenderTexture self)
    8. {
    9.     if (self.format == RenderTextureFormat.ARGB32) return self;
    10.     RenderTexture result = RenderTexture.GetTemporary(self.width, self.height, 0, RenderTextureFormat.ARGB32);
    11.     Graphics.Blit(self, result);
    12.     return result;
    13. }
    14.  
     
unityunity