8-bit PNG in WordPress – an Issue with File Sizes

I just came across with a PNG compression issue that appears to be a bug in how WordPress core handles 8-bit / 256 colors PNG image files.
The screenshots used on this site’s web design references are saved as PNGs instead of JPGs because of the transparent background that PNG format allows for.
There are lots and lots of sites that have PNGs for other reasons also – mostly because many people like to capture quick screenshots that Mac / OSX saves as PNGs. These files are by design lossless and therefore rather large in kilo-bytes. This is bad because large files cause longer page load times, which in turn negatively affect SEO and users’ perception of a site’s performance.
If you go one step further and know how to optimise image files in Photoshop, you’ll be later caught by a surprise: The conversion / compression logic of WordPress, which creates the other file sizes, fails to keep the 8-bit / 256 colors format and instead creates PNGs that are much larger files in kilo-bytes.
An example:
339K image-8bit-1024x520.png
22K image-8bit-150x150.png
730K image-8bit-1536x780.png
38K image-8bit-300x152.png
210K image-8bit-768x390.png
269K image-8bit-768x432.png
296K image-8bit-800x450.png
382K image-8bit-800x600.png
160K image-8bit.png
The first column above is the file size in kilobytes, the second column is for the file names; those with the width x height suffix are generated by WordPress core. The originally uploaded file (without the suffix) is 1600×812 pixels.
The 1536×780 pixels sized file is 4.5 times larger than the original 1600×812 pixels!
To overcome this issue, you may do something counterintuitive. Instead of requesting image sizes such as ‘medium_large’ for 768px wide files, set the code to call for ‘full’, which fetches the original files in 8-bit / 256 colours. Even they’re larger in their pixel size, they’re smaller in bytes and therefore load faster.
This is an old bug in WordPress core, reported first time in 2016. It seems to affect all image file generation, be it with the simple image upload or WP-CLI command wp media regenerate
.