Search Unity

EncodeToPNG doesn't create alpha channel?

Discussion in 'Scripting' started by jister, Oct 25, 2017.

  1. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    or does it? i'm confused.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEditor;
    5. using System.IO;
    6.  
    7. public class SavePNG : EditorWindow
    8. {
    9.     private Texture2D texture;
    10.  
    11.     [MenuItem("Window/SavePNG")]
    12.     static void Init()
    13.     {
    14.         SavePNG window = (SavePNG)EditorWindow.GetWindow(typeof(SavePNG));
    15.         window.Show();
    16.     }
    17.     void OnGUI()
    18.     {
    19.         if(GUILayout.Button("Create texture"))
    20.         {
    21.             texture = new Texture2D(2048,2048, TextureFormat.RGBA32, false);
    22.             Color32 c = new Color(1,0,0,1);
    23.             Color32[] colors = texture.GetPixels32();
    24.             for(int i=0; i<colors.Length; i++)
    25.             {
    26.                 colors[i] = c;
    27.                 colors[i].a = (byte)(1f*i/colors.Length);
    28.             }
    29.             texture.SetPixels32(colors);
    30.             texture.Apply();
    31.         }
    32.  
    33.         EditorGUILayout.ObjectField("texture", texture, typeof(Texture2D));
    34.  
    35.         if(GUILayout.Button("Save texture"))
    36.         {
    37.             byte[] bytes = texture.EncodeToPNG();
    38.             File.WriteAllBytes(Application.dataPath + "/Texture.png", bytes);
    39.             AssetDatabase.Refresh(ImportAssetOptions.ForceUncompressedImport);
    40.             Debug.Log(texture.format);
    41.  
    42.         }
    43.     }
    44. }
    45.  
    in Unity it shows RGBA32 format and has a Alpha channel.
    If i open it up in Photoshop, its totally blank transparent without Alpha Channel?

    anyone knows what's going on?
     
    MaxGuernseyIII likes this.
  2. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
    (byte)(256f * i / colors.Length);
     
  3. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    thats just to give some variation in the alpha, doesn't matter if it's there. Have the same problem without any colors changes.
     
  4. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
    Odd.

    When I made that change, I got an alpha channel. I don't know anything about photoshop but the alpha was clearly visible in the Unity editor. What version of Unity are you using? Whatever the answer, your solution might just be upgrading to 2017.2...
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Code (csharp):
    1. colors[i].a = (byte)(1f*i/colors.Length);
    Color32 is 0-255, not 0.0-1.0. You're setting the alpha for every pixel to 0.

    --Eric
     
    jister and MaxGuernseyIII like this.
  6. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
    @Eric5h5 is right. You should listen to him. ;)
     
  7. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    hahaha yes i forgot thanks, i was wondering why they stayed black :p
    but that still doesn't solve my problem :(
     
  8. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
    Right...yet it does work on v2017.2, like I said in my original reply.
     
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Keep in mind that when you open a PNG with an alpha channel in photoshop it does NOT appear transparent anywhere.

    You have to look over in the alpha channel (channels tab) to see it, but the window remains fully opaque. It's apparently by design but I find it maddening when I'm using Photoshop.

    Try opening the alpha PNG with the Gimp image program and you will see the alpha "holes."

    EDIT: correction! Apparently the latest Photoshop does show transparencies properly. I know that older version do not. Not sure how much older...
     
    Last edited: Oct 25, 2017
  10. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    this is what i get when saving a png in unity
    in Unity it shows correct:
    SplatUnity.PNG
    the alpha channel is there:
    SplatUnityAlpha.PNG
    this is how i get it in PS:
    SplatAlpha.PNG

    it does seem to work correct in unity thou...
     
    MaxGuernseyIII likes this.
  11. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    bump...
    Every PNG i save is messed up :(
    made a flowmap painter to paint on rivers inside unity and if i open it in unity i get the same result as my above post, desperately need a solution...
     
  12. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
    What I don't get is that your exact code, with that one line fixed, generates a .PNG with transparency. So either you aren't running the fixed version of the code, you aren't measuring the transparency correctly, or there is something different about your environment than everyone else's.

    Which of those possibilities would you like help further investigating?
     
  13. McDev02

    McDev02

    Joined:
    Nov 22, 2010
    Posts:
    664
    To me it looks fine, what do you expect to get exactly? Photoshop displays PNGs only the way you see above, it does not support seperated alpha channels for pngs. If you need the alpha chanel seperated then you have to open the map in a different programm or save something else as png.
    You could store the RGB map and the Alpha in two different JPGs with Quality setting of 100. Then import to Photoshop, put the mask in a seperate channel and then save as a TGA.

    Unity should add a EncodeToTGA(), that would be neat.
    EDIT: Oh look, maybe try this?
     
    Last edited: Nov 8, 2017
    lordofduct, Kurt-Dekker and jister like this.
  14. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    yes i changed to the jpg method, didn't know PS doesn't support alpha channel in png o_O
    and i vote YES on the EncodeToTGA() :)
    EDIT: Oh wow thanks for the link!!!
     
  15. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    I think the thing you're missing is that alpha is used as transparency in Photoshop. That's what it's supposed to look like. Anywhere the alpha channel is black is transparent, and anywhere it's white is opaque. That's how transparency usually works. If you want to ignore the alpha channel in Photoshop I think there's a command somewhere to just turn it off but at the moment I don't remember where.
     
    MaxGuernseyIII likes this.
  16. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Cue a close-in camera view of @McDev02 saying "There's a script for that..." :)

    Thanks! Good to have around. TGA is my preferred format because it's super-simple.
     
  17. McDev02

    McDev02

    Joined:
    Nov 22, 2010
    Posts:
    664
    I tested the script now and it works fine. But I thought the Alpha handling isn't good so I added a boolean "storeAlpha" to the Method and replaced "_texture2D.format == TextureFormat.ARGB32" with that boolean.
    Whatever people say, TGA is still the best format for textures.
    BTW: If you save PNGs in Photoshop and transparency is 0 then color information is lost. So only use PNGs if alpha is transparency. For UI sprites it is the preferrred format, but not for textures.
     
    jister likes this.
  18. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    the problem was that there isn't a alpha channel present in PS...? no idea why not btw.
     
  19. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Yes there is. That image you posted is showing transparency. See those grey and white squares in the background? Those are not actually part of the image, that is Photoshop's "transparent background". It's trying to show you that most of the image is transparent and the only parts that aren't transparent are where you see colors. If you copy and paste that image on top of a different image in Photoshop, it only pastes the non-transparent parts. You won't see the grey and white squares anymore. Transparency and alpha channel are the same thing in Photoshop. You said you're making a Flow Map and they use alpha channels for something else, but that's a very edge case. MOST of the time, with images, alpha means transparency.
     
  20. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    I think he means there's no alpha channel in the Channels window.
     
    jister likes this.
  21. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    I don't know, everyone saying "Yeah that exported image must be broken, try a whole different script that uses TGA instead" and the OP all seem to be failing to understand that the exported PNG is perfectly fine. So I decided to just google the answer (I suggest everyone learn to use google ;) ) and in Photoshop for a PNG, to edit the alpha go to Layer > Layer Mask > From Transparency.
     
    KelsoMRK and McDev02 like this.
  22. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Nobody has said the exported image is broken (aside from the OP at first), and we all know the exported PNG is fine. ;) You're apparently missing that people were talking about Photoshop's behavior when showing PNG files with transparency. The fact is that it does not handle PNGs as a flattened image with a separate alpha channel. A TGA image does. It's true that you can convert a PNG with transparency to flattened-with-alpha, but that's extra steps which TGA does not need.

    --Eric
     
    Kurt-Dekker likes this.
  23. McDev02

    McDev02

    Joined:
    Nov 22, 2010
    Posts:
    664
    I googled that numerous times and only got those "Photoshop doesn't handle seperate Alpha" answers. I until then only copeid the layer enough times to make it opaque. But this works even for full transparent areas.
    Still for export it is not a good idea to use PNGs if Alpha is anything else than transparency because Photoshop will erase color information if Transparency is 0.
     
    Last edited: Nov 10, 2017
  24. Noisecrime

    Noisecrime

    Joined:
    Apr 7, 2010
    Posts:
    2,054
    I'm somewhat disappointed that so many people recommend TGA, as I find it a horrible format with no native thumbnail support in Windows and extremely poor compression compared to PNG.

    As to the issues of viewing PNG in Photoshop, the default behavior as noted by many replies here is to encode the alpha channel as transparency. Sometimes this is desirable, sometimes it isn't. Thankfully this is a painless way to get both behaviors in Photoshop and that is to install the SuperPNG plugin. ( download it from here )

    You can set up the default behavior to either open PNG with alpha as transparency or alpha as separate alpha channel. In addition when saving to SuperPNG it allows you to save alpha as transparency or as an alpha channel. You can also hold down ctrl ( I think) when opening a PNG and choose the desired behavior.

    Just remember to always save as superPNG and not PNG ( photoshops default).

    Personally I couldn't bear working without PNG's they offer great compression and with the plugin allow you to have the best of both worlds.
     
    Peter77 likes this.
  25. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,539
    Considering that Unity handles the content pipeline for all textures and recompresses them into a format appropriate for the target platform.

    The compression size of the local image really only impacts the size of your project while working on it... and not the target size of the compiled build.

    ...

    With that said, I don't really know much about the differences of formats from an artist perspective... but instead from the technical specs of them (how to encode to them... and even then only for the formats I bother to look up).

    But my artist lol'd at PNG.

    "Sure, if you wanna smash your alpha into an interlaced transparency!"

    Whatever that means...

    Well, I know what he means by it technically.

    But yeah... PNG doesn't actually have an "alpha channel". Instead it has transparency. And you might say "well that's what alpha is!". But it's not. The alpha channel can store any data really... and that's what photshop sees the alpha channel as, just another channel.

    PNG on the other hand doesn't do this. Instead the transparency is stored as either a mask, or as part of the colour palette. When treated as a mask, it acts like a localized alpha channel for a region (and is fat). Or it's just treated as part of the colour information in the palette.

    This ladder is the reason my artist says "Sure, if you wanna smash your alpha into an interlaced transparency!"

    What he means is that when it's part of the colour information. You're essentially losing the colour information. If you think of colour channels as the various opacities of a colour, the transparency is a cap on that. So basically... the so called 'alpha' is part of the colour information. (which is what he means by interlaced transparency, the alpha information is interlaced into the colour information... not to be confused with a different usage of interlaced which png also supports).

    So yeah, Photoshop doesn't unravel the transparency information into its own channel since it's really just part of the colour information. You'd actually lose colour information if you did this.

    My artist says this is why he prefers TGA (and other formats, just not PNG). It allows him to work on a per channel basis cleanly without fear of any lossy conversion occurring (he's a pro with nearly 20 years experience, he has his methods for a reason I guess).

    ...

    From what I gather about SuperPNG, it exploits the alternative 'mask' feature of PNG for transparency. Which as far as I can tell adds a little bit of bloat in an attempt to create what sort of acts more like an alpha channel.

    Which is an issue. You have to 'force' or 'trick' the PNG into saving the mask. It wants to "smash" everything, since it's trying to compress. I guess SuperPNG works around this tendency of it. But from an engineering perspective who has to design things for artists to use... that leaves a giant hole to trip over and cause data loss with no easily understandable reason for said data loss.

    ...

    But eh. As he said... why try to hack PNG to get an alpha channel by installing a weird plugin. When you could just install a plugin that gives thumbnail support for TGA (and tiff, and other artist centric formats).

    He uses SageThumbs:
    https://sourceforge.net/projects/sagethumbs/

    ...

    And like I said, since Unity translates the texture images when building anyways. The compression of PNG really doesn't matter that much when it comes to 'build size'. Only when it comes to 'project size'. And well... in this day of massive storage devices, and the fact the textures aren't really the largest portion of our project, we're not that hyper concerned about that.

    The convenience's he gains (he can directly work with all 4 channels directly without the added effort of re-exporting and crushing his alpha every time) speeds up his workflow while maintaining a lossless format, far outweighs the cost of a few more megabytes on our storage drive. I have 10 terrabytes on our version control server... I don't think we're running out any time soon.

    ...

    But eh, to each their own on their own workflow.
     
    Last edited: May 9, 2018
  26. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,539
    Thanks for this link.

    I just created a tool for my artist today, but it lacked tga support. This gives it to him.

    WIN!
     
  27. McDev02

    McDev02

    Joined:
    Nov 22, 2010
    Posts:
    664
    In Photoshop you have options to save PNGs and using things like interlaced is not right for textures. That is stuff for the Web. Also I hate pngs, it might be small but have many issues. Just that saving a 2k or even 4k png can take a lot of time. They are perfect for Sprites though.
     
  28. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,539
    Note, in my post, I reference back to his usage of that word.

    When he said 'interlaced' he didn't mean that feature you're speaking.

    Here is where I mentioned it:
    That feature has to do with supporting rendering a png when it's not fully loaded. And when used in that context that's what it refers to.

    But he was using the word in the context of smashing alpha channels into transparencies. Which is technically independent of PNG, but is done by PNG.

    It's like how if you say 'interface' you may refer to interfaces in respect the the construct in C#... or in the context of programming in general. C# has both (the concept, and the construct), but the concept could be referenced independent of C#.

    Such multi-purpose words come up a lot between he and I. He uses the words in a more 'artist' context, we do in a more 'technical' context.
     
    Last edited: May 9, 2018
  29. ACap

    ACap

    Joined:
    Feb 8, 2013
    Posts:
    1
    To see png alpha channel it in Photoshop - Go to: Layer - Layer Mask - From Transparency.