Featured image of post imagejpg-imagepng-imagegif Can Generate Images but Fail to Output to Browser

imagejpg-imagepng-imagegif Can Generate Images but Fail to Output to Browser

UTF-8+BOM Encoding Causes Image Display Issues

If your imagejpg, imagepng, or imagegif functions can generate images but fail to display them in the browser, this article will help you resolve the issue.

Initially, I compared a working file with the problematic one and found no visible differences - not even a single character.

Undeterred, I downloaded a text comparison tool. The truth gradually emerged:


As shown, the left (working) file uses standard UTF-8, while the right (problematic) file uses UTF-8 + BOM.

Key differences between the encodings:

UTF-8+BOM includes a three-byte prefix (0xEF 0xBB 0xBF) absent in standard UTF-8. While this prefix helps programs automatically detect UTF-8 encoding, it causes critical issues in PHP:
The extra three bytes trigger output before PHP’s header() function, violating its requirement of “no output before headers”. This prevents proper image rendering in browsers.

Solution: Convert file encoding to standard UTF-8 (without BOM) using your code editor or IDE.