Traditionally, I would have answered in the same way as NetWallah
did in his reply
. That is: send the HTML file with a link to the image, for which you don't even need to use CGI. That's how we've done it for almost 20 years already.
But in the modern world, there is another option, and that is much closer to your own solution, and that is to embed the PNG file into your HTML. For that, you have to base-64 encode your image file data, slap a content-type in a form of header on it and put that as the source of the <img> tag, using the data: protocol. The code could look like this:
printf '<img src="data:image/png;base64,%s">', encode_base64($image);
where the rest of you code can remain the same.
I would not recommend this for huge files, as it increases the transfer byte size by 33%, but for tiny images of a few k at most that is definitely a good alternative, since it limits the number of server requests.