In answer to your question about what was wrong with the code, it simply didn't produce anything at all. But after some experimentation, I think it must be a context problem. If I put the code directly into the image.php page, it works. Ideally, however, I need to put the code in a file that is being added via an include. Is there a way to do that while maintaining context, or do I have to move all the code to the image.php page? Obviously, the latter would be a bummer since it would mean that I have to maintain duplicate code.
EDIT: the above was written before seeing Acrylian's post. i guess i have to move the code since i'm assuming there's no way to do what i asked above. is that correct?