I have found a workaround, which is to store the file-generating PHP script on a different domain and server (along with the JPG htaccess trick I described above).
My original problem only seems to occur when the script is on the same domain, which causes it to fetch the file directly/locally instead of fetching it like a normal URL.
To me this workaround is preferable to writing code for WordPress 'hooks' etc. which are more complicated to understand, and are liable to change and require rewriting the code over time to maintain compatibility.