PNG file grows in Unity after applying downloaded texture and convert back to PNG via EncodeToPNG

If you precisely inspect both PNG files, you will notice the difference. Both of them have same resolution, same bit depth, some number of channels, and both are not interlaced.

However, the original image contains only one IDAT section which holds 41370 bytes of encoded data.

The image originating from Unity contains 8 IDAT sections: 7 x 8192 bytes and one 2860 bytes, 60204 bytes altogether.

In the PNG specification, there is a note:

Multiple IDAT chunks are allowed so that encoders can work in a fixed amount of memory; typically the chunk size will correspond to the encoder's buffer size.

Furthermore, the data contained in those IDAT sections is not necessarily exact the same for the same source images. Those IDAT sections hold raw byte data which was first pre-filtered and then encoded using the zlib compression.

So, the PNG encoder can choose the pre-filtering algorithm from 5 available ones:

Type    Name

0       None
1       Sub
2       Up
3       Average
4       Paeth

Additionally, the zlib compression can be configured for compression window size, which can also be chosen by the PNG encoder.

Inspecting the zlib streams gives following results:

  • both files use "deflate" compression with same window size 32k
  • the compression flags are, however, different - original file has compression level 1 (fast algorithm) whereas the Unity encoded file has compression level 0 (fastest algorithm).

This explains the differences in the binary data and data size.

It seems that you have no control over Unity's PNG encoder, so unfortunately you cannot force it to choose another zlib algorithm.

I suppose, the same happens with the JPEG files - the encoder just chooses a faster algorithm that produces a larger file.

If you want to be in full control of PNG-encoding in Unity, you need to implement your own PNG encoder. E.g. here on Unity forum, there is a sample of such a PNG encoder that uses the zlib.net library. You can fine tune the encoding e.g. by specifying the zlib compression algorithm.